Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA The Drunkard\'s (Random) Walk. Imagine you live on an infinite grid of s

ID: 3760422 • Letter: I

Question

IN JAVA

The Drunkard's (Random) Walk. Imagine you live on an infinite grid of streets where locations are represented as integer pairs (avenue,street). Negative numbers are okay in this example. Now consider a drunkard that randomly picks one of four directions at an intersection and then stumbles to the next intersection doing the same and so on. Write a class Drunkard to simulate this behavior given the drunkard's initial position. Should Have

1) as instance variables the drunkard's current avenue (x location) and current street (y location)

2) a method called step( ) that moves the drunkard to the next randomly chosen adjacent intersection.

3) method called fastForward(int steps) that takes an integer as input (call it steps) and moves the drunkard steps intersections from his current location

4) method getLocation( ) that returns a String indicating the drunkard's current location

5) method called howFar( ) that reports the drunkards distance in blocks from where he started calculated using the Manhattan distance metric (http://xlinux.nist.gov/dads//HTML/manhattanDistance.html ).

Explanation / Answer

import java.util.Random;

public class Drunkard {

int xCur;

int yCur;

int xStart;

int yStart;

// create a constructor where instance variables are initialized

public Drunkard (int avenue, int street) {

xStart = avenue;

yStart = street;

xCur = avenue;

yCur = street;

}

// the step method is used to choose random number to decide which direction drunkard goes on the grid

public void step() {

// to choose a random number between 0 and 4

Random rand = new Random();

// we set this randomly chosen # to an int variable

int pickedNumber = rand.nextInt(4);

// if statements for four possible intersection cases that can be possible

if (pickedNumber == 0)

{ xCur ++;

}

if (pickedNumber == 1)

{xCur = xCur - 1;

}

if (pickedNumber == 2)

{yCur ++;

}

if (pickedNumber == 3)

{yCur = yCur - 1;

}

}

// method that will make the step method run steps number of times

public void fastForward(int steps) {

// for loop which will make the step method execute steps # of times

for (int counter = 1; counter <= steps; counter ++) {

step();

}

}

// method which will give current/final location & returns that sting to the tester

public String getLocation() {

String location = yCur + " streets and " + xCur + " avenues"

return location; }

// method that will calculate the distance and then return the value to tester

public int howFar() {

int distance = Math.abs(xCur - xStart) + Math.abs(yCur - yStart);

return distance;

}

}