Gabrielus - 3 months ago 10

Java Question

Problem: I want to generate random locations on a grid which are touching. The total number of locations is 5. Is there a more efficient/different way of doing the following code:

`/*`

* 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--;

}

Answer

I would advise on the use of `Random.nextInt(8)`

Vs `Math.random()*8`

(see here why). Because your current requirements seem to allow one "seed" only, you could declare a `static Random random = new Random();`

in your class, so you just call `random.nextInt(8)`

in your method.

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

As you may notice, the above has the same impact with your approach, but uses the modulo operation mainly for readability purposes, cause *mod* is not as fast as an `if`

checking.

Small Edit by OP: (result of random represented graphically on x and y axis)

```
6 3 0
5 [origin] 2
4 7 1
```