The program assignment:
A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. Represent locations as integer pairs (x,y). Implement the drunkard's walk over 100 intersections, starting at (0,0) and print the ending location.
I created this Drunkard class:
import java.util.*;
class Drunkard {
int x, y;
Drunkard(int x, int y) {
this.x = x;
this.y = y;
}
void moveNorth() {
this.y -= 1;
}
void moveSouth() {
this.y += 1;
}
void moveEast() {
this.x += 1;
}
void moveWest() {
this.x -= 1;
}
void report() {
System.out.println("Location: " + x + ", " + y);
}
}
And this DrunkardTester class to test the above class
import java.util.Random;
public class DrunkardTester {
public static void main(String[] args) {
Random generator = new Random();
Drunkard drunkard = new Drunkard(0, 0);
int direction;
for (int i = 0; i < 100; i++) {
direction = Math.abs(generator.nextInt()) % 4;
if (direction == 0) { // N
drunkard.moveNorth();
} else if (direction == 1) { // E
drunkard.moveEast();
} else if (direction == 2) { // S
drunkard.moveSouth();
} else if (direction == 3) { // W
drunkard.moveWest();
} else {
System.out.println("Impossible!");
}
}
drunkard.report();
}
}
It complies and runs fine, and it prints a different coordinate location each time I run it, but I just wanted to get a few other pairs of eyes on it to see if there are any glaring errors.
Also, on my DrunkardTester class is there anyway to eliminate the "Impossible!" else statement? I wasn't really sure if that was necessary or what else could be put there.
generator.nextInt(MAX_DIRECTION)where MAX_DIRECTION is an int constant and == 4. \$\endgroup\$ifbranches, but you might consider replacing the multi-partifwithswitch. \$\endgroup\$