# 我怎样才能产生一个范围内的随机数字，但排除一些？

``public int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) { int random = start + rnd.nextInt(end - start + 1 - exclude.length); for (int ex : exclude) { if (random < ex) { break; } random++; } return random; }` `

` `int[] ex = { 2, 5, 6 }; val = getRandomWithExclusion(rnd, 1, 10, ex)` `

` `val = getRandomWithExclusion(rnd, 1, 10, 2, 5, 6)` `

` `/** * @param start start of range (inclusive) * @param end end of range (exclusive) * @param excludes numbers to exclude (= numbers you do not want) * @return the random number within start-end but not one of excludes */ public static int nextIntInRangeButExclude(int start, int end, int... excludes){ int rangeLength = end - start - excludes.length; int randomInt = RANDOM.nextInt(rangeLength) + start; for(int i = 0; i < excludes.length; i++) { if(excludes[i] > randomInt) { return randomInt; } randomInt++; } return randomInt; }` `

` `List<Number> numbers; numbers.add(1); numbers.add(2); numbers.add(3); //You can do a "for" without adding the excluded numbers.. //Then, your randomizer could be... public Number getRandoNumber() { int index = Random.get(0, numbers.size()); return numbers.get(index); }` `

` `Collections.shuffle(numbers); public Number getRandomNotRepeat() { if(numbers.size() == 0) throw new RuntimeException("No more numbers"); Number n = numbers.get(0); numbers.removeFirst(); return n; }` `

` `rand(1,9); rand(15,19); rand(22,26);` `

` `int i = rand(1, 9); if i>=7 i++; return i;` `

` `public int getRandomNumberWithExclusion( int start, int end ) { Random r = new Random(); int result = -1; do { result = start + r.nextInt( end - start ); }//do while( !isAllowed( result ) ); return result; }//met private boolean isAllowed( int number ) { //your test for restricted values here }//met` `

` `private int GiveMeANumber(int range,int... exclude) { Set<Integer> integers=new HashSet<>(); int count=range; for(int i=0;i<count;i++) integers.add(i); integers.removeAll(Arrays.asList(exclude)); int index = new Random().nextInt(range - exclude.length); count=0; for (int value:integers){ if(count==index) return value; count++; } return 0; }` `