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

A drunkard in a grid of streets randomly picks one of four directsions and stumb

ID: 3560288 • Letter: A

Question

A drunkard in a grid of streets randomly picks one of four directsions 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.

Here is the code I used. The problem is when I run the program I only get either the x or y value to change and not both values at the same time. What do I need to change so both values change?

import java.util.*;

public class intersection

{

public static void main(String args[])

{

int x = 0;

int y = 0;

  

System.out.println("Initial point is ("+x+","+y+")");

  

Random rand_obj = new Random();

int direction,distance;

  

for(int i=0; i<100; i++)

{

direction = rand_obj.nextInt(4);

distance = rand_obj.nextInt(100);

  

if(direction == 0)

x = x + distance;

else if(direction == 1)

y = y + distance;

else if(direction == 2)

x = x - distance;

else

y = y - distance;

}

  

System.out.println("Final point is ("+x+","+y+")");

}

}

Explanation / Answer

/*find the required solution run it and notice the change

Note:bolded the changes*/

import java.util.*;

public class Intersection

{

public static void main(String args[])

{

int x = 0;

int y = 0;

  

System.out.println("Initial point is ("+x+","+y+")");

  

Random rand_obj = new Random();

int direction,distance;

  

for(int i=0; i<100; i++)

{

direction = rand_obj.nextInt(4);

distance = rand_obj.nextInt(100);

  

if(direction == 0)
{
x = x + distance;
y = y - distance;
}
else if(direction == 1)
{
   x = x -distance;
   y = y + distance;
}

else if(direction == 2)
{
x = x + distance;
x = x +distance;
}

else
{
   x = x - distance;
y = y - distance;
}
}

  

System.out.println("Final point is ("+x+","+y+")");

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote