Hello Looking a simple algorithm and Java code for this I a

Hello. Looking a simple algorithm and Java code for this -- I am just having trouble organizing this:

Imagine yourself in the middle of Manhattan, where the streets are perpendicular on avenues. You are in a grid of streets, somewhat lost, and you randomly pick one of four directions and walk to the next intersection. Not knowing where you really want to go, you again randomly pick one of the four directions, and so on. After repeating the same movement for a number of times, you may want to know how far you got from the original point.

Represent locations as integer pairs(x,y). Create an algorithm that implements your movement through New York City, over 100 intersections, starting at (0,0) and print the ending location, taking into consideration that each movement, from one intersection to another will be one mile.

Thank you

Solution

/*

-- Algorithm --

0 - left
1 - right
2 - front
3 - back

*/

/*

0 - left
1 - right
2 - front
3 - back

*/

/* Considering
0 - left
1 - right
2 - front
3 - back
*/
import java.util.Random;

public class HelloWorld{
public static void main(String []args){
int i,x = 0, y = 0, rand = 0;
Random ran = new Random();
for(i=0;i<100;i++)
{
rand = ran.nextInt(4); // generates random number in between 0 and 3
  
if(rand == 0) // left
x--;
else if(rand == 1) // right
x++;
else if(rand == 2) // front
y++;
else // back
y--;
  
}
// printing output
System.out.printf(\"You started at (0,0) and after 100 miles, now at (%d,%d)\ \",x,y);
}
}

/* You started at (0,0) and after 100 miles, now at (-2,-4) */

Hello. Looking a simple algorithm and Java code for this -- I am just having trouble organizing this: Imagine yourself in the middle of Manhattan, where the str
Hello. Looking a simple algorithm and Java code for this -- I am just having trouble organizing this: Imagine yourself in the middle of Manhattan, where the str

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site