Taken from DailyCodingProblem
Using a function
rand7()
that returns an integer from1
to7
(inclusive) with uniform probability, implement a functionrand5()
that returns an integer from1
to5
(inclusive).
Solution
This is the answer I came up with:
// typescript
function rand5(): number {
return Math.ceil(Math.random() * 5)
}
This is a really simple question, and I didn’t feel satisfied so I also implemented a solution that returns a random (inclusive) integer but guarantees that the integer remains unique until the entire range is exhausted – that is,
rand(10)
below would never return a duplicate number until all numbers from1
through10
have also been previously returned.
const set = new Set()
function rand(_number: number): number {
// If full (all numbers have been previously returned), clear the set
if (set.size === _number) {
set.clear()
}
let random = Math.ceil(Math.random() * _number)
let regen = () => {
random = Math.ceil(Math.random() * _number)
}
while (set.has(random)) {
// Regenerate the random number if it's already in the set
regen()
}
// Add the random number to the set before returning
set.add(random)
return random
}
Testing
Solution tested in REPL:
https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAJwIZgCYFYAUBKALkTBAFsAjAU2UQG8AoRFSqEZJAWVSgAsA6CJRgAbHF1580mOKXyIAVIix56AX3r1hLRDEQBeRAAZ6Adx4jKiHLoA8iAEyG8dRoggIAznC19hcAOY4Utj4KkwwANQRavRAA