I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?
function generateRandom(mi
I have answered a similar question for Java: Generate random numbers except certain values. I just copy and paste the answer as follows.
Actually, we do not need to use
contains(random)with a while loop.To simplify the question, let's see what happens if we only have one excluding value. We can split the result to
2parts. Then the number of possible values isrange-1. If the random number is less than the excluded value, just return it. Otherwise, we could add1.For multiple excluding values, We can split the result set into
size+1parts, wheresizemeans the number of excluding values. Then the number of possible values isrange-size. Then we sort excluding values in ascending order. If random number is less than the excluding value minusi, then we just return the random number addi, whereiis the index of the the excluding value.public int generateRandomNumberWithExcepts(int start, int end, Listexcepts) { int size = excepts.size(); int range = end - start + 1 - size; int randNum = random.nextInt(range) + start; excepts.sort(null); // sort excluding values in ascending order int i=0; for(int except : excepts) { if(randNum < except-i){ return randNum + i; } i++; } return randNum + i; }