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--;
}
Gabrielus
  • 416
  • 4
  • 13
  • 1
    What do you mean by "touching"? Could you give a sample output? – Tunaki Jan 26 '16 at 13:39
  • do you use the "rank" variable after that? or it's only for picking a random int [1,8]? Could you post the whole method? – Kostas Kryptos Jan 26 '16 at 14:36
  • @tunaki choose a location as specified (like 1-8) at random and then use the location specified to generate another location – Gabrielus Jan 26 '16 at 15:19
  • @Konstantinos Chalkias the rest of the code simply maps out the drawn shape in a jframe for the user to see. It's part of a game – Gabrielus Jan 26 '16 at 15:21

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,939
  • 3
  • 25
  • 45
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
  • 3,959
  • 2
  • 22
  • 23