简体   繁体   中英

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. 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

I am quite sure that I'm about 95% done. However, I need an array to store bool values, to see if the ant has visited the square on the board or not. I can't really figure out how to do it. Ignore the "isVisited", it was my first idea.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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