Search code examples
functionprobabilityprobability-theory

find new function using given function that generates twice the output of given function


Given a function that generates numbers from 1 to 6 with equal probability. Find a function by doing operations on given function such that it produces numbers from 1 to 12 with equal probability.

My approach: I was maintaining a count variable. If count is an even number then I was adding 0 else I was adding 6 to f(). But there are unlimited number of calls to f() so, we can't use count variable.


Solution

  • Let f6() be the function that generates values from 1 to 6 with equal probability. We can call f6() twice and store the result in two separate variables a and b.

    Now by using the expression (a + (b&1)*6), we can generate numbers from 1 to 12 with equal probability.

    Explanation:

    a and b will range from 1 to 6. since f6() is generating numbers with equal probability.

    (b&1) will return either 0 or 1 equally likely depending on whether b is even or odd respectively.

    Now, In case b&1 is 0, we will have range from 1 to 6 since the (b&1)*6 = 0. So, result can only be the values 1, 2, 3, 4, 5, 6.

    And in case b&1 is 1, result can only be the values 7, 8, 9,10, 11, 12 as (b&1)*6 = 6.