生成与二维数组中最后一组数字仅相差 1 的数字集

Generate sets of numbers which only have a difference of 1 from the last set of numbers in a 2d array

问题:我想在网格上生成随机位置,这些位置是相互接触的。位置总数为5。是否有更多efficient/different方法来执行以下代码:

 /*
 * 8        1       2
 * 7    [original]  3
 * 6        5       4
 */


int rand = 1 + (int)(Math.random() * ((8 - 1) + 1));
if(rand >= 2 && rand<= 4)
{
    newx++;
}
else if(rand >=6 && rand<=8)
{
    newx--;
}

//change y according to number
if(rand == 8 || rand == 1 || rand==2)
{
    newy++;
}
else if(rand >= 4 && rand<= 6 )
{
    newy--;
}

根据 this Threadswitch 声明似乎对您的情况更有效。它还使您的代码更具可读性。

switch (rand){
    case 1:         newy++; break;
    case 2: newx++; newy++; break;
    case 3: newx++;         break;
    case 4: newx++; newy--; break;
    case 5:         newy--; break;
    case 6: newx--; newy--; break;
    case 7: newx--;         break;
    case 8: newx--; newy++; break;
}

我建议使用 Random.nextInt(8)Math.random()*8(参见 here 原因)。因为你目前的要求似乎只允许一个 "seed",你可以在你的 class 中声明一个 static Random random = new Random();,所以你只需在你的方法中调用 random.nextInt(8)

int rand = random.nextInt(8); //0..7
if (rand < 3) //0,1,2
{
    newx++;
}
else if (rand < 6) //3,4,5
{
    newx--;
}

//change y according to number
if(rand % 3 == 0) //0,3,6
{
    newy++;
}
else if(rand % 3 == 1) //1,4,7
{
    newy--;
}

您可能会注意到,上述方法与您的方法具有相同的影响,但使用 modulo 操作主要是为了提高可读性,导致 modnot as fast 作为 if 检查。

OP 的小编辑:(在 x 轴和 y 轴上以图形方式表示的随机结果)

  6         3       0
  5      [origin]   2
  4         7       1