// Imports
import java.util.concurrent.ThreadLocalRandom;

// Main Class
class calcPi {
  //Main Function
  public static void main(String [] args) {

    // Thread Vars
    int threadnum = 1;
    CalcThread[] threads = new CalcThread[51];

    // pi Value
    double pi = 0;

    // Timer Vars
    double startTime;
    double endTime;

    // Validate user input
    try {
      threadnum = Integer.parseInt(args[0]);
      if (threadnum > 50){
        throw new Exception();
      }
    } catch (Exception e) {
      System.out.println("Please enter a number from 1-20");
      System.exit(1);
    }

    // Get program start time
    startTime = System.currentTimeMillis();

    // Generate Threads
    for (int x = 0; x < threadnum; x++){
      threads[x] = new CalcThread(threadnum);
      threads[x].start();
    }

    // Wait for threads to die
    try{
      for (int x = 0; x < threadnum; x++){
        threads[x].join();
      }
    } catch (Exception e){
      System.out.println("OOP!");
    }

    endTime = System.currentTimeMillis();

    endTime = (endTime / 1000) - (startTime / 1000);

    String stringTime = String.format("%.3f", endTime);
    

    // Get the pi value from each thread and take the average
    for (int x=0; x < threadnum; x++){
      pi = pi + threads[x].pi;
    }
    pi = pi / threadnum;

    // Print stats
    System.out.println("Run Stats");
    System.out.println("----------------------");
    System.out.println("Time: " + stringTime);
    System.out.println("Threads: " + threadnum);
    System.out.println("Value of pi: " + pi);

    // Exit Program
    System.exit(0);
  }
}

class CalcThread extends Thread {
  boolean negative = true;
  double pi; // Initializes to 0.0, by default
  double rx;
  double ry;
  double d;
  int threads;
  int hits = 0;
  int total = 0;

  CalcThread(int threadnum){
    threads = threadnum;
  }

  public void run ()
  {
    for (int i = 1; i < 100000000/threads; i++) {
      rx = ThreadLocalRandom.current().nextDouble(0,1);
      ry = ThreadLocalRandom.current().nextDouble(0,1);
      d = Math.sqrt((Math.pow(rx,2) + Math.pow(ry,2)));
      if (d < .5){
        hits++;
      }
      total++;
    }
    pi =(double) hits/total * 16;
  }
}
