I’m writing a typical 2-D random walk. However, the cursor can only move in cardinal directions. I wrote this method to test the code but it doesn’t exclude diagonal moves (when the x and y values are equal). That’s where I’m stuck. I could select a random integer between 1 and 4 and use nested ifs, but it seems there should be a simpler way using Boolean types since it's a binary decision. Am I on the right track?
for (int i = 1; i <= 10; i++) {
//assume x & y are already initialized
Random xmove = new Random();
Random ymove = new Random();
// select new x-coord
if (xmove.nextBoolean()) {
x += 1;
} else {
x += -1;
}
// select new y-cord
if (ymove.nextBoolean()) {
y += 1;
} else {
y += -1;
}
System.out.printf("(%d, %d)", x, y);
System.out.println();
}
Aucun commentaire:
Enregistrer un commentaire