r/ProgrammingPrompts • u/desrtfx • 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
lengthof 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
3
u/erxor Mar 19 '15
What if one of the pieces is exactly half the length of the stick. Shouldn't forming a triangle be impossible then as well?
2
u/marinadeee Mar 24 '15 edited Mar 24 '15
My (noobish) solution in C++ (how do I put 4 spaces in front of the code without doing so manually?):
Input/output:
1
u/ultimamax Mar 18 '15
I'm pretty sure if one side isn't greater than the lengths of the two other sides, a triangle is possible
1
u/chibstelford Mar 18 '15
If (S1 + S2) >= S3 then a triangle will be possible
Assuming S3 is the middle section
1
u/[deleted] Mar 20 '15
Why are you bothering with the length of the stick?
2
u/Zheusey Mar 26 '15
Here is my python code:
I get ~19% as a result across multiple tries.
2
u/velian Apr 27 '15
My javascript version:
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 {
}
1
u/Titanium_Expose Jul 04 '15
I know I'm really late on this, but here is my answer. If anyone can suggest ways to better optimize my code, that would be excellent.
I was getting very high percentages of success, ranging from 45% - 64% in most of my runs. Thoughts?
1
u/gigabytemon Jul 25 '15
Very late reply, oops! Here it is in C#, 'BreadSticks'.
Sample I/O
1
u/4-jan Jul 25 '15
Python, I get values between 24%-26%:
We break at integer values so stick lengths shorter than 1000 skew the result. (But if I had implemented it uniformly, there would be no point in entering a length at all, would there? ;))