I need help for this question. I need it to run in Java, not in C++ The Drunkard
ID: 3531970 • Letter: I
Question
I need help for this question. I need it to run in Java, not in C++
The Drunkard's Walk. 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 actually 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.
Explanation / Answer
Sorry i messed it up
here it is
THIS IS WHAT YOU NEED:
no changes required
starting position is (0,0)
every intersection he picks up randomly in all 4 directions , not only north and east...
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 moveEast() {
this.x += 1;
}
void moveWest(){
this.x -=1;
}
void moveSouth(){
this.y -=1;
}
void report() {
System.out.println("location is:" + x + ", " + y);
}
}
class Direction {
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();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.