简体   繁体   中英

Java Antwalk - 2D Arrays

There is a 2D array with dimensions 9x9. The ant starts in cell (5,5) , or the center. It moves randomly north, south, east, or west. The ant stops walking when it falls off the grid. The space where it falls is marked by an X. In the matrix, it should display the amount of times the ant visited each cell and the number of moves the ant took to fall off.

I'm not sure where to start or how to go about it. Like how to make the north, south, west, east methods.

Here's what I have so far.

public static void main(String [] args)
{
    int [][] grid = new int[9][9];

    for (int r = 0; r< grid.length; r++)
    {
        for (int c = 0 ; c<grid[0].length; c++)
        {
            grid[r][c] = 0;
        }
    }

    boolean test = true;
    while(test)
    {
        int random =  (int)Math.random()*4+1;
        if (random == 1)
        {

        }
        else if (random == 2)
        {

        }
        else if (random == 3)
        {

        }
        else if (random == 4)
        {

        }
    }
}

You've got the right idea, now what you want to do is move in the direction specified by random, and increment the value in your array. Here is how I would do it.

int count = 0;
int x = 4;
int y = 4; // arrays are 0 based
while(true)
{
    int random =  (int)Math.random()*4+1;
    if (random == 1)
    {
        x--; // move left
    }
    else if (random == 2)
    {
        x++; // move right
    }
    else if (random == 3)
    {
        y--; // move down
    }
    else if (random == 4)
    {
        y++; // move up
    }
    if(x < 0 || y < 0 || x >= grid.length || y >= grid[x].length) break;
    count++;
    grid[x][y]++;
}
System.out.println(count); // number of moves before it fell

Here is a random walk of an ant on the grid. See comments in the code. The ant walks STEPS on a predefined size grid.

import java.util.Random;

public class Ants {

    /** height and width of the grid */
    public static final int HEIGHT = 9 ;
    public static final int WIDTH  = 9 ;

    /** NOVAL means "no value" */
    public static final int NOVAL  = -1;

    /** world directions */
    public static final int NORTH  = 0 ;
    public static final int WEST   = 1 ;
    public static final int SOUTH  = 2 ;
    public static final int EAST   = 3 ;

    /** how many steps for ant to walk */
    public static final int STEPS   = 10;

    /** where does the ant start it's walk */
    public static final int START_X = 5;
    public static final int START_Y = 5;

    /** printing related */
    public static final String ANT  = "ANT";

    private static final Random random = new Random();

    /** grid for ant to walk on */
    static int[] grid;

    /** get height of the grid */
    static int getHeight() {
        return HEIGHT;
    }

    /** get width of the grid */
    static int getWidth() {
        return WIDTH;
    }

    /** size of the grid */
    static int getSize() {
        return getWidth()*getHeight();
    }

    /** coordinates are converted to one dimension */
    /** @return index from coordinates. */
    static int idx(int x, int y) {
        return y*getWidth() + x;
    }

    /** get x coordinate of idx */
    static int x(int idx) {
        return idx % getWidth();
    }

    /** get y coordinate of idx */
    static int y(int idx) {
        return (idx - x(idx)) / getWidth();
    }

    /** get cell */
    static int getCell(int idx) {
        return grid[idx];
    }
    static int getCell(int x, int y) {
        return getCell(
                idx(x,y));
    }

    static void setCell(int idx, int value) {
        grid[idx] = value;
    }

    /** init array with some value */
    private static void initArr(int[] arr, int value) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = value;
        }
    }

    /**
     * @return adjancted cells indexes.
     */
    public static int[] adjanctedTo(int idx) {
        int[] adj = new int[4];
        initArr(adj, NOVAL);

        int x = x(idx);
        int y = y(idx);

        /** Is North available? */
        if (y - 1 >= 0) {
            adj[NORTH] = idx(x,y-1);
        }
        /** West? */
        if (x - 1 >= 0) {
            adj[WEST] = idx(x-1, y);
        }
        /** South? */
        if (y + 1 < getHeight()) {
            adj[SOUTH] = idx(x,y+1);
        }
        /** East? */
        if (x + 1 < getWidth()) {
            adj[EAST] = idx(x+1, y);
        }

        return adj;
    }

    /** picks random value from array */
    public static int pick(int[] arr) {
        int ret = NOVAL;
        int idx = random.nextInt(4);

        for (int i = idx;; i++) {
            if (NOVAL != arr[i]) {
                ret = arr[i];
                break;
            }
            if (3 == i) {
                /** cycle if not yet found a NOVAL value in array */
                i = 0;
            }
        }

        return ret;
    }

    public static void main(String[] args) {

        /** init grid */
        grid = new int[getSize()];

        int nextStep = NOVAL;
        int current  = idx(START_X, START_Y);
        setVisited(current);

        for (int s = 0; s < STEPS; s++) {
            System.out.println("STEP "+s);
            System.out.println(
                    "Standing @" + position(current) + ".");
            printGrid(current);

            nextStep = pick(
                    adjanctedTo(current));

            System.out.println(
                    "Moving to " + position(nextStep));
            setVisited(current);
            printGrid(nextStep);

            current = nextStep;
        }
    }

    public static void setVisited(int idx) {
        setCell(idx, getCell(idx)+1);
    }

    public static String position(int idx) {
        return idx+"("+x(idx) + ";" + y(idx) +")";
    }

    public static void printGrid(int antPosition) {
        for (int x = 0; x < getWidth(); x++) {
            for (int y = 0; y < getHeight(); y++) {
                if (idx(x,y) == antPosition) { 
                    System.out.print(ANT);
                } else {
                    System.out.format(
                            "%2d|",
                            getCell(x,y));
                }
            }
            System.out.println();
        }
    }

}

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