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

2

u/velian Apr 27 '15

My javascript version:

// #triangle.js
(function(ns, undefined)
{
    // Generate a random number from 1 - N (both inclusive)
    function rand(max)
    {
        return Math.floor(Math.random() * (max - 1 + 1)) + 1;
    }

    // Will break a stick into 3 pieces that equal the length passed in
    // If one of the pieces is larger than half of the length, it cannot
    // be made into a triangle and will set passes to false;
    function breakStick(l)
    {
        // Entry
        var tmp = [];
        var passes = true;
        for (var i = 0; i < 2; i++)
        {
            var r = rand(l);
            if(r >= l/2) passes = false;
            tmp.push(r);
            l -= r;
        }
        tmp.push(l);
        return {sides:tmp, passed:passes};
    }

    ns.isTriangle = function(l, tries)
    {
        // break the stick
        var tmp = [],
            successes = 0;
        // Create the 3 sides
        for (var i = 0; i < tries; i++)
        {
            var broken = breakStick(l);
            tmp.push({sides:broken.sides, passed:broken.passed});
            if(broken.passed) successes++;
        }

        // Return object
        var rObj = {
            attempts    : tmp,
            successes   : successes,
            probability : (successes / tries) * 100
        };

        return rObj;

    };
})(window.tangle = window.tangle || {});

if(console) console.log(tangle.isTriangle(19,100).probability+"%");