Transforming a random number generator to another scale
Let’s say you have a random number generator which generates random numbers between 1 to 7 and you need to transform it to generate random numbers between 1 to 10?
Well, I faced a similar problem recently and this is quite easy than it looks on the face. We have:
rand7() -> 1 to 7 // we already have this
rand10() -> 1 to 10 // we need to write this
Think about it for a while.
I first started with scaling up the numbers which it was giving me and also thought of how I can use an approach where I can use multiple of these in conjunction to write sophisticated (read complex) random number generator. Turned out, the answer is quite simple. I won’t even explain my solution, but I’ll present directly the pseudo code.
lastReturned := 0rand10():
lastReturned := lastReturned + rand7()
lastReturned := lastReturned % 10 # to scale between 0 to 9
lastReturned := lastReturned + 1 # since we need from 1 to 10
return lastReturn
This gives us the same distribution as the method rand7
gives us.
Similarly, we can also scale down any random number generator. Here’s a Github Gist for this.