No, it’s not the most recently leaked Tarantino Screenplay. I’m of course referring to a challenging conundrum my bootcamp cohort friend showed to me. The problem is a little lax on wording but I’ll try to interpret it the best I can. Simply put, the challenge says,
“Given a function rand5(), implement rand7()”
By rand5() they mean a random integer between 1 and 5, inclusive. I completed this task using ruby, so I’ll present the necessary code to complete using THEIR wording.
rand(5) won’t work because it includes ‘0’.
When I first started thinking about this problem, I was confused as to what I would need to do because it seems impossible that given an assortment of 5 possible random outcomes, one could generate a random number between 1 and 7. I started considering strange possibilities, but the answer was right under my nose. Using the .sample method on an array of arrays. See below.
rand7 = [
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]
]
100.times { puts rand7[rand((1..5))-1].sample }
By utilizing the rand5() concept to randomize an array’s index, you can just use sample to call a random 1-7.
I also wanted to do the same using the true ruby method rand(5) => rand(7), so that’s below:
rand7 = [
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6]
]
100.times { puts rand7[rand(5)].sample }
I realize this way may seem easier than people have made the problem, but if I’m understanding it correctly, it doesn’t need to be that hard.
