How can I generate a random number within a range but exclude some, without keep generating and checking if the generated number is one of those that I want to exclude?
How can I generate a random number within a range but exclude some, without keep generating and checking if the generated number is one of those that I want to exclude?
This is the most reliable way to do it.
Create an array with your range, remove all excluding elements
Choose a random index and return the value from that position.
public int getRandomNumber(int start, int end, List<Integer> excludingNumbers) {
int[] range = IntStream.rangeClosed(start, end).toArray();
List<Integer> rangeExcluding = Arrays.stream( range ).boxed().collect( Collectors.toList() );
rangeExcluding.removeAll(list);
int newRandomInt = new Random().nextInt(rangeExcluding.size())
return rangeExcluding.get(newRandomInt);
}
Range includes start and end
example: val random = arrayOf((-5..-1).random(), (1..10).random()).random()
In this example you exclude 0 in numbers between -5 and 10