package edu.bloomu.ch6c;

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Calculates the expected length of a random walk from the center of a circle to its 
 * boundary. 
 * 
 * @author Drue Coles
 */
public class RandomWalk {

    public static void main(String[] args) {
        System.out.print("Enter radius of circle: ");
        Scanner in = new Scanner(System.in);
        int radius = in.nextInt();

        final int walks = 1000; // the number of random walks to simulate
        int totalSteps = 0; // total number of steps over all walks
        for (int i = 0; i < walks; i++) {
            totalSteps += randomWalk(radius);
        }
        
        // Calculate the expected length of a walk by averaging over all walks.
        int avgSteps = totalSteps / walks;
        System.out.printf("Expected length of random walk: %d steps.%n", avgSteps);
    }   
    
    /**
     * Simulates a random walk from the center of a circle to its boundary.
     * 
     * @return number of steps taken
     */
    private static int randomWalk(int radius) {
       int steps = 0;
       int x = 0; // x-coordinate of current position
       int y = 0; // y-coordinate of current position
       
       // Each iteration of the loop corresponds to one step in a random direction.
       ThreadLocalRandom rand = ThreadLocalRandom.current();
       double distance = 0; 
       while (distance < radius) {
           
          int dir = rand.nextInt(4); 
          if (dir == 0) {
             x++;
          }
          if (dir == 1) {
             x--;
          }
          if (dir == 2) {
             y++;
          }
          if (dir == 3) {
             y--;
          }
          
          distance = Math.hypot(x, y);
          steps++;
       }
       
       return steps;
    }
}