A drunkard in a grid of streets randomly picks one of four d

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.

Notes:

the canvas dimensions are 800 x 572, so the center point is at (400, 286)

CPS JAVA

Solution

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);

}

}

Drunkard tester:

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();

}

}

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, a
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, a

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site