【问题标题】:Java Antwalk - 2D ArraysJava Antwalk - 二维数组
【发布时间】:2013-12-02 05:00:16
【问题描述】:

有一个尺寸为 9x9 的二维数组。蚂蚁从单元格 (5,5) 或中心开始。它随机向北、向南、向东或向西移动。当蚂蚁从网格上掉下来时,它就停止了行走。它落下的空间用 X 标记。在矩阵中,它应该显示蚂蚁访问每个单元格的次数以及蚂蚁落下的移动次数。

我不确定从哪里开始或如何着手。比如北、南、西、东的制作方法。

这是我目前所拥有的。

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)
        {

        }
    }
}

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    您的想法是对的,现在您要做的是沿随机指定的方向移动,并增加数组中的值。以下是我的做法。

    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
    

    【讨论】:

    • int x 和 int y 代表什么?
    • int x 和 int y 是蚂蚁在数组中的 x 和 y 位置。 (笛卡尔坐标系)它们代表蚂蚁当前所在的点。我们通过改变它的 x 和 y 值来移动蚂蚁。然后我们检查 x 和 y 值是否在数组之外,在这种情况下,我们停止移动蚂蚁,因为它已经掉出来了。
    • 由于网格[x][y]++,我不断收到越界错误;部分。
    【解决方案2】:

    这是一只蚂蚁在网格上的随机游走。请参阅代码中的 cmets。蚂蚁在预定义大小的网格上行走 STEPS。

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

    【讨论】:

      【解决方案3】:
      public static void main(String[] args) {
          String[][] sim = ant(3,3);
          for (int i = 0; i < sim.length; i++) {
              for (int j = 0; j < sim[i].length; j++) { 
                  System.out.print(sim[i][j] + " "); 
              }
              System.out.println();
          }
      }
      static String[][] ant(int x, int y) {
          if(x<0||x>=9||y<0||y>=9){
              return null;
          }
          int[] rn = {-1, 1}; //next ant random direction , you can include 0 if you wanted
          String[][] mat = new String[9][9];
          for (int i = 0; i < 9; i++) {
              Arrays.fill(mat[i], "0");//fill array with 0 to avoid null default value
          }
          int a = x, b = y; // a and b are the Cartesian coordinates of the ant
          while (true) {  
              mat[a][b] = String.valueOf(Integer.parseInt(mat[a][b]) + 1); 
      
              int newx = a + rn[(int) (Math.random() * rn.length)];
              int newy = b + rn[(int) (Math.random() * rn.length)];
              //these are the ant new coordinates , we have to check them before going to them
              if (newx < 0 || newx >= 9 || newy < 0 || newy >= 9) {
                  mat[a][b] = "X";
                  return mat;
              }
              a = newx;
              b = newy;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-29
        相关资源
        最近更新 更多