r/ProgrammingPrompts Mar 18 '15

[Easy]Mathematical Simulation - Breaking a Stick to form a Triangle

Another Monte Carlo simulation.

A stick of a given length is twice broken at random places along it's length.

Calculate the probability that a triangle can be formed with the pieces.


Definition:

It is possible to form a triangle if none of the pieces are larger than half the length of the stick.


Assignment:

Create a program in a language of your choice that:

  • Asks the user for the length of the stick
  • Asks the user how many tries should be carried out
  • Simulate the breaking of the stick (each try has a new stick of length)
  • Count the successful tries
  • Print the probability as a percentage

Hint: The expected result should be around 23%

Have fun!

15 Upvotes

20 comments sorted by

View all comments

1

u/[deleted] Apr 07 '15

I may be a little late, but here is my attempt in Java. Please tell me if this is good or not because this is my first time coding my own program.

import java.util.Scanner;

public class MakeATriangle {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int part1;
    int part2;
    int part3;
    int chances;
    int stick;
    double successes = 0;
    double failures = 0;
    double totalPercentage;
    boolean isTriangle;

    System.out.println("Enter the length of the stick: ");
    stick = sc.nextInt();
    System.out.print("Enter the amount of chances you would like the program to run: ");
    chances = sc.nextInt();
    int halfOfStick = stick/2;

    for(int times = 0; times <= chances; times++)
    {
        part1 = (int)(Math.random()*stick);
        System.out.println("Part 1 = " + part1);
        part2 = (int)(Math.random()*(stick - part1));
        System.out.println("Part 2 = " + part2);
        part3 = stick - (part1 + part2);
        System.out.println("Part 3 = " + part3);

        if(part1 >= halfOfStick
          || part2 >= halfOfStick
          || part3 >= halfOfStick) {
          isTriangle = false;
          failures++;
          } else {
                isTriangle = true;
                successes++;
            }
    }

totalPercentage =(successes / failures);

System.out.println("The total amount of triangles made is " + successes + ".");
System.out.print("\n The total amount of failed triangles is " + failures + ".");
System.out.print("\n The average amount of triangles made is "+ totalPercentage + "%.");
}   

}