I know how to random number using java Random class.
This will random a number between 0-13 13 times;
public static void main(String[] args) {
int ctr = 13;
int randomNum = 0;
while(ctr != 0) {
Random r = new Random();
randomNum = r.nextInt(13);
ctr--;
System.out.println(ctr +": " + randomNum);
}
}
Question
-I would like to random a number between 0-13 for 13 times
-If the first random number is e.g(5),then my second random number will random any number from 0-13 again EXCLUDING 5;
If the second random number is e.g(4),then my third random number will random any number from 0-13 again EXCLUDING 5 and 4; etc.. is there a way to do it?
Do this:
List
of size 13In code:
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 13; i++)
nums.add(i);
Collections.shuffle(nums);
for (int randomNum : nums)
System.out.println(randomNum); // use the random numbers
I'd fill a list, shuffle it, and then iterate it, guaranteeing a different number each time:
public static void main(String[] args) {
int ctr = 13;
List<Integer> list = new ArrayList<>(ctr);
for (int i = 0; i < ctr; ++i) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < ctr; ++i) {
System.out.println(ctr + ": " + list.get(i));
}
}
Question -I would like to random a number between 0-13 for 13 times
I would start with a List
and Collections.shuffle(List)
and a Random
with something like -
Random rand = new Random();
List<Integer> al = new ArrayList<>();
for (int i = 0; i < 14; i++) {
al.add(i);
}
Collections.shuffle(al, rand);
System.out.println(al);
Or, if using Java 8+, an IntStream.range(int, int)
to generate the List
. And you could use a forEachOrdered
to display (and in either version, you cold use the Collections.shuffle
with an implicit random) like
List<Integer> al = IntStream.range(0, 13).boxed().collect(Collectors.toList());
Collections.shuffle(al);
al.stream().forEachOrdered(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With