1) Yes, all numbers between 1
to k
will have the same probability to appear, and that probability will be 1 / k
(not 1 / n
), so they all are equally probable (also, if k - n
is high, then the number of calls to f() inside fn() may increase).
2) Create a x-tuple of values (f(), f(), ..., f())
, where x is the smaller integer that satisfies the following in-equation: kx >= n
We only care about x such that kx > n, which will turn the problem back to case 1 (where k > n
). If the generated x-tuple is outside the first n tuples, start again.
Example: Given f() that returns a number in [1, 5]
(equally probable), you want to create fn() that returns a number in [1, 10]
(also equally probable).
The first integer x that satisfies 5x >= 10 is x = 2, (25 >= 10).
Then your x-tuple is of the form (f(), f())
(just a tuple), call the function f() twice and apply case 1:
(1,1) = 1, (1,2) = 2, (1,3) = 3,
(1,4) = 4, (1,5) = 5, (2,1) = 6,
(2,2) = 7, (2,3) = 8, (2,4) = 9 and (2,5) = 10
If you get one of the other 15 tuples [(3,1),(3,2),(3,3),(3,4),(3,5),(4,1),(4,2),(4,3),(4,4),(4,5),(5,1),(5,2),(5,3),(5,4),(5,5)] repeat the algorithm again until you get one the first 10 tuples.
The 10 tuples have the same probability of 1/25 to appear.