0

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--;
}
Gabriel Stellini
  • 426
  • 4
  • 13

2 Answers2

2

According to this Thread a switch statement seems to be more efficient for your case. Also it makes your code way more readable.

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;
}
Community
  • 1
  • 1
ArcticLord
  • 3,999
  • 3
  • 27
  • 47
1

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
Community
  • 1
  • 1
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24