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

Consider a sailor who gets out of a bar completely drunk, in a city where all bl

ID: 3670632 • Letter: C

Question

Consider a sailor who gets out of a bar completely drunk, in a city where all blocks are in perfect squares with size 1×1. The drunken sailor walks from one corner of a block to the next. When in a corner, he forgets where he came from, and where he was going. He takes a direction at random, either north, east, south, or west, with an equal probability of 25%. Then in the following corner he again forgets where he was going, but keeps on walking by following a random direction. You will write a program that takes an integer input N, and simulates the motion of the drunken sailor for N steps. After each step, print the location of the sailor. You can treat the starting point as (0,0). Also, print the nal distance from the origin and the furthest point1 he has reached.

What I have done so far is code a string that generates a random number which dictates the change in position of x and y. Ig. 0<x<0.25 would be moving right, 0.25<x<0.5 would be moving left.

import java.util.Random;


public class DrunkenSailor {
  
public static void main(String[] args) {
  
Random rand = new Random();
float randomFloat = rand.nextFloat();
  
System.out.println(randomFloat);
  
}
  
private static void log(String aMessage){
System.out.println(aMessage);
}
}

Explanation / Answer

import java.util.Random;
import java.io.*;

public class DrunkenSailor {

   public static void main(String[] args) throws IOException {
       InputStreamReader ir=new InputStreamReader(System.in);
       BufferedReader br=new BufferedReader(ir);
       System.out.println("Enter the number of steps");
       int n=Integer.parseInt(br.readLine());
       int x=0,y=0;
       int fx=0,fy=0;
       double farthest=0;
       for(int i=0;i<n;++i)
       {
           Random rand = new Random();
           float randomFloat = rand.nextFloat();
           if(randomFloat<0.25)
           {
               x=x+1;
           }
           else if(randomFloat<0.50)
           {
               x=x-1;
           }
           else if(randomFloat<0.75)
           {
               y=y+1;
           }
           else
           {
               y=y-1;
           }
           double dist=Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
           if(dist>farthest)
               farthest=dist;
               fx=x;
               fy=y;
           System.out.println("Position after "+i+1+"step is ("+x+","+y+")");
       }
       double distOrigin=Math.sqrt(Math.pow(x,2)+Math.pow(y,2));

       System.out.println("Distance from origin is "+distOrigin);
       System.out.println("Farthest Distance travelled "+farthest);
       System.out.println("Farthest location ("+fx+","+fy+")");

   }

   private static void log(String aMessage) {
       System.out.println(aMessage);
   }
}