简体   繁体   English

如何更改二维布尔数组的值?

[英]How to change value of 2D bool array?

I have this assignment for school:我有这个学校的作业:

Imagine a chess board and an ant.想象一个棋盘和一只蚂蚁。 The ant is randomly put on the board and after that it can walk up, down, left and right (not diagonally).蚂蚁被随机放在板上,然后它可以上下左右(不是对角线)行走。 The ant cannot walk over the edge of the chess board (if it tries, it is not counted as a movement).蚂蚁不能越过棋盘的边缘(如果它尝试,则不算作移动)。 The task is to create a program called Ants.java that simulates the walking over the chess board of an ant.任务是创建一个名为 Ants.java 的程序,该程序模拟蚂蚁在棋盘上行走。 To walk to another square than the one the ant is currently on is called a “step” (even though it will take the ant several steps to move…).走到另一个方格而不是蚂蚁当前所在的方格被称为“一步”(即使蚂蚁需​​要几步才能移动......)。 Each simulation should calculate the number of “steps” the ant takes to visit all squares on the chess board.每次模拟都应计算蚂蚁访问棋盘上所有方格所需的“步数”。 The simulations must be done ten times and an average should be calculated at the end of the simulation.模拟必须进行十次,并应在模拟结束时计算平均值。 An example run of the simulation is shown below:模拟运行的示例如下所示:

Ants蚂蚁

Number of steps in simulation 1: 708 Number of steps in simulation 2: 818 Number of steps in simulation 3: 953 Number of steps in simulation 4: 523 Number of steps in simulation 5: 671 Number of steps in simulation 6: 338 Number of steps in simulation 7: 535 Number of steps in simulation 8: 702模拟 1 中的步数:708 模拟 2 中的步数:818 模拟 3 中的步数:953 模拟 4 中的步数:523 模拟 5 中的步数:671 模拟 6 中的步数:338模拟 7 中的步数:535 模拟 8 中的步数:702

I am quite sure that I'm about 95% done.我很确定我已经完成了大约 95%。 However, I need an array to store bool values, to see if the ant has visited the square on the board or not.但是,我需要一个数组来存储 bool 值,以查看蚂蚁是否访问了板上的正方形。 I can't really figure out how to do it.我真的不知道该怎么做。 Ignore the "isVisited", it was my first idea.忽略“isVisited”,这是我的第一个想法。

This is my code right now:这是我现在的代码:

public static void main(String[] args) {
    // Sums every step in the 10 iterations
    double totalNumber = 0;
    boolean[][] grid = new boolean[8][8];
        for (int r = 0; r< grid.length; r++)
        {
            for (int c = 0 ; c<grid[0].length; c++)
            {
               grid[r][c] = false;
            }
        }
    // Just a loop to make the ant walk 10 times
    for (int k = 1; k <= 10; k++) {


        // Setting board to false, not visited
    boolean isVisited = false;

    // Creating spawn points
    int x = (int) (Math.random() * (8 + 1)) + 1;
    int y = (int) (Math.random() * (8 + 1)) + 1;
    // Setting spawn point to 
    isVisited = true;


    // Variables, steps, min coord and max coords
    int count = 0;
    int minY = 1;
    int maxY = 8;
    int minX = 1;
    int maxX = 8;

    // All the unchecked places
    int unchecked = 64;
    // Places where the ant has been
    int alreadyChecked = 0;

    // While there's more than 0 unchecked places, random 1 - 4
    while (unchecked > 0) {
        int random = (int) (Math.random() * 4 + 1);

        // West
        if (random == 1) {
            // Move to the left
            x--;
            // If the ant falls off
            if (x < minX) {
                // Bump it back
                x++;
            }

            // If the place is visited
        if (isVisited) {
            // Already checked
            alreadyChecked++;
            // Count step anyway
            count++;
        }
        // If it's not
        if(!isVisited) {
        // Set to visited
            isVisited = true;
            // Remove 1 from the unchecked
            unchecked--;
            // And take a step
            count++;
        }

        }

        // East
        if (random == 2) {
            x++;
            if (x > maxX) {
                x--;

            }

            if (isVisited) {
                alreadyChecked++;
                count++;
            }
            if(!isVisited) {
            isVisited = true;
            unchecked--;
            count++;
            }

        }

        // North
        if (random == 3) {
            y++;
            if (y > maxY) {
                y--;
            }
            if (isVisited) {
                alreadyChecked++;
                count++;
            }

            if(!isVisited) {
        isVisited = true;
        unchecked--;
        count++;
            }
        }

        // South
        if (random == 4) {
            y--;

            if (y < minY) {
                y++;
            }
            if (isVisited) {
                alreadyChecked++;
                count++;
            }


                isVisited = true;
                unchecked--;
                count++;
        }



}
    /**
 * This simulation assumes Ant movement is discrete relative to grid cells
 * i.e. its either in one of these cells at a time, overlapping two cells in not allowed!!
 * **/
public class AntMovementSimulation 
{
    int onBoard[][] = null;
    int antPosX = 0;
    int antPosY = 0;
    int antPrevPosX = 0;
    int antPrevPosY = 0;

    int directionOfMovement = 0;
    int stepsCount = 0;

    AntMovementSimulation()
    {
        onBoard = new int[8][8];
        //initialize each position in onBoard to -1 ,implying Ant has not been placed yet, not even once!!
        for( int i = 0 ; i < 8 ; i++ )
        {
            for( int j = 0 ; j < 8 ; j++ )
            {
                onBoard[i][j] = -1;//implying Ant has not been placed yet, not even once!!
            }
        }

        //place Ant in random cell
        antPosX = (int)Math.round(Math.random()*7);//generating random number between 0 and 7, since index is from 0 to 7 as there are 8 cell!!
        antPosY = (int)Math.round(Math.random()*7);
        //assigning 1 to onBoard at index antPosX,antPosY to indicate Ant has been placed there
        onBoard[antPosX][antPosY] = 1;
    }

    /*this function returns false if any cell has -1,else true
     * cause when all cells have been traversed , each cell have non negative value,either 0 or 1 
     *  */
    public boolean areAllCellsTraversed()
    {
        boolean result = true;

        for( int i = 0 ; i < 8 ; i++ )
        {
            for( int j = 0 ; j < 8 ; j++ )
            {
                if( onBoard[i][j] == -1 )//implying this cell not traversed yet,i.e Ant not placed in this cell yet!!
                {
                    result = false;
                }
            }
        }
        return result;
    }

    public void simulate()
    {
        //loop while all cells have been not traversed
        while( !areAllCellsTraversed() )
        {
            directionOfMovement = (int)Math.round(Math.random()*3);//generating random number between 0 and 3
            switch( directionOfMovement )
            {
            case 0://move left-to-right
                antPosX += 1;
                if( antPosX >= 7 ) antPosX = 0; //since largest array index is 1 less than its size, we compare with 7 instead of 8                 
                break;

            case 1://move right-to-left
                antPosX -= 1;
                if( antPosX <= 0 ) antPosX = 7;                 
                break;

            case 2://move top-to-bottom
                antPosY += 1;
                if( antPosY >= 7 ) antPosY = 0;                 
                break;

            case 3://move bottom-to-top
                antPosY -= 1;
                if( antPosY <= 0 ) antPosY = 7;                 
                break;
            }

            //assign 0 to previous position, meaning Ant is no longer there
            onBoard[antPrevPosX][antPrevPosY] = 0;
            //assign 1 to new position , meaning Ant is here
            onBoard[antPosX][antPosY] = 1;

            stepsCount++;
            antPrevPosX = antPosX;
            antPrevPosY = antPosY;                  
        }   
        //once all cells have been traversed , print result!!
        printSteps();
    }   

    /*prints the total number of step taken to traverse all cells*/
    public void printSteps()
    {
        System.out.println("Total steps taken by Ant to traverse all cells = "+stepsCount);
    }

    public static void main(String[] args)
    {
        int sumOfTotalNumOfSteps = 0;
        AntMovementSimulation[] amsArray = new AntMovementSimulation[10];
        for( AntMovementSimulation ams: amsArray )
        {
            ams = new AntMovementSimulation();
            ams.simulate();
            sumOfTotalNumOfSteps += ams.stepsCount;
        }
        System.out.println("Average num of steps taken by Ant to traverse all cells = "+ sumOfTotalNumOfSteps/10);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM