Improved the code I wrote earlier. As an improvement point --Using Set instead of List to reduce the number of retries --The number you want to exclude is Interger type instead of String type
main.java
import java.util.Random;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int i;
//Store the number you want to exclude
Set exSet = new HashSet();
exList.add(2);
exList.add(5);
exList.add(8);
do {
i = Interger.valueOf(rand.nextInt(10)+1); // 1~Generate random numbers up to 10 and convert to strings
} while (exSet.contains(i)); //Repeat if it matches any of the numbers in the exclusion list
System.out.println(i);
}
}
Here is the code before improvement
main.java
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String i;
//Store the number you want to exclude
List<String> exList = new ArrayList<String>();
exList.add("2");
exList.add("5");
exList.add("8");
do {
i = String.valueOf(rand.nextInt(10)+1); // 1~Generate random numbers up to 10 and convert to strings
} while (exList.contains(i)); //Repeat if it matches any of the numbers in the exclusion list
System.out.println(i);
}
}
I also found a way to exclude random numbers excluding specific numbers found on QA sites overseas. I will post it for reference.
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;
}
main.java
int[] ex = { 2, 5, 6 };
val = getRandomWithExclusion(rnd, 1, 10, ex)
// 5,6,When a random number of 7 is generated, the value of 7 is acquired, so the frequency of occurrence is high only for 7.
Recommended Posts