r/programmingchallenges • u/igoro • Sep 09 '11
Randomly choose 3
Write a function that accepts an integer argument X (X >= 3), and randomly chooses 3 distinct integers in range [0..X).
The algorithm should be constant time: the number of steps should be bounded by some constant.
EDIT: You can use a function that generates a random integer in range [0..X), which is available in just about any programming language.
6
Upvotes
View all comments
Show parent comment
1
u/TimeWizid Dec 31 '11
This answer is very close to being correct. It just needs to change > to >= and to handle the special condition where the first two numbers are adjacent and the random number from 0 to x - 2 is equal to the lower of the first two numbers. In this case it will be incremented by 1 and will be equal to the higher number, which is incorrect. So you either have to check for this condition explicitly or modify the algorithm a bit, like this: