Consider yourself driving with 60 miles/hour in a city that has only grid like s
ID: 3863853 • Letter: C
Question
Consider yourself driving with 60 miles/hour in a city that has only grid like streets, and your GPS is broken. The specifications of the problem are: With (x, y) as the coordinates of the car, consider the initial position (0, 0). At each intersection, the only directions available are North, South, East or West The GPS is broken, and it chooses the direction randomly at each intersection, which happens every 5 minutes The assumption is that the car has the same speed at all times, including when it changes direction and turns. Write a program that calculates the direct distance from the initial point to the location point of the driver after one hour of driving (i.e. the distance between two points).Explanation / Answer
Direction changes in every 5 mins; So after 1 hour, the direction will be changed 60/5 = 12 times.
code.java
package javaapplication1;
public class code {
public static void main(String[] args)
{
int x = 0;
int y = 0;
for(int i = 0; i < 12; i++)
{
int rand = (int )(Math.random() * 4 );
if(rand == 0) //right
{
x = x +1;
}
else if(rand == 1) // left
{
x = x-1;
}
else if(rand == 2) //up
{
y = y-1;
}
else if(rand == 3) //down
{
y = y+1;
}
}
double d = Math.sqrt(x*x + y*y);
System.out.println("Distance between initial and end point is: " + d);
}
}
Sample Output:
Distance between initial and end point is: 2.8284271247461903
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.