Java 棋盘上的蚂蚁

Java 棋盘上的蚂蚁,java,arrays,Java,Arrays,目前我的程序总是只给我4个,我如何确定蚂蚁采取了多少步骤来覆盖整个电路板?蚂蚁可以左右行走,但不能从板上走下来,然后进行4次模拟 public static void main(String args[]) { int[][] grid = new int[8][8]; int count = 0; int x = 0; int y = 0; // arrays are 0 based while(true) { int rand

目前我的程序总是只给我4个,我如何确定蚂蚁采取了多少步骤来覆盖整个电路板?蚂蚁可以左右行走,但不能从板上走下来,然后进行4次模拟

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

    int count = 0;
    int x = 0;
    int y = 0; // 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("Number of Steps in this simulation: " + count); // number of moves before it fell
    }
}

问题在于这个表达式:

int random =  (int)Math.random()*4+1;
通过显式强制转换,只有Math.random ist被强制转换为int。但是由于Math.random返回的dobule<1,它被强制转换为0,因此random始终为1,并且该方法始终返回0

该问题可以通过铸造Math.random*4来解决:

括号强制将Math.random*4的值转换为int,该值将是区间[0,3]中的值

关于您的代码,请注意两点:

我建议引入一个枚举方向,每个方向有四个值,并通过调用Direction.values[int Math.random*4]选择一个随机方向; 我建议使用一个开关,而不是if-else-if级联。 一旦4个条件之一为真,程序将退出whiletrue循环。我的建议是在ifrandom==值检查中移动这些条件,如下所示:

if( random == 1 )
 {
   x--;
   if (x < 0 )
    {
      x++;
    }
 }
但是请注意whiletrue循环中的许多ifs语句。如果你必须填充一个10行x 10列的板,那么在填充板之前需要花费太多的时间。相反,我建议你使用一些更有效的算法,如回溯、动态规划等


编辑:添加了步数计数器。

我对执行枚举方向不是很有信心。有什么建议吗?代码很棒!但由于某些原因,我得到了例外。一旦4个条件之一为真,程序将退出whiletrue循环。-这是不正确的。条件2和4将导致进一步的迭代。覆盖整个电路板,但c“不从板上走”让我想到蚂蚁一直走到它盖住板为止,当它要从板上走下来时,它什么也不做。结果应该显示蚂蚁走了多少步才能盖住整个板,如果它要掉下来,那么它不算一步,但不会掉下来,它又回到了尝试c然后我建议采纳我的建议,删除最后一个if的条件,并尝试在普通if语句上使用一些更有效的算法,或者至少使用@Turing85-suggest来使用switch语句。@CyT3如果程序应该运行到每个字段至少被访问一次,那么您的代码远远不是一个简单的if语句粘连。
if( random == 1 )
 {
   x--;
   if (x < 0 )
    {
      x++;
    }
 }
int stepsTaken = 0;
int cellsToCover = grid.length * grid[0].length ;
int coveredCells = 0;
while(true)
{
 //your code here
 if( random == 1 )
  {
    stepsTaken++;
    x--;
    if (x < 0 )
    {
      x++;
    }
  }
  // the other if's with "stepsTaken" incremented too.
  if ( grid[x][y] == 0 )
  {
    grid[x][y] = 1;
    coveredCells++;
  }
  if (coveredCells == cellsToCover )
    break;
 }