Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

don't random number that are being random before

Tags:

java

random

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?

like image 719
user3820292 Avatar asked Aug 03 '14 05:08

user3820292


3 Answers

Do this:

  • Create a List of size 13
  • Fill it with numbers 0-12
  • Shuffle the List using the JDK Collections utility method
  • Use the numbers in the shuffled order (by just iterating over the List)

In 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
like image 112
Bohemian Avatar answered Nov 19 '22 06:11

Bohemian


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));
    }
}
like image 31
Mureinik Avatar answered Nov 19 '22 05:11

Mureinik


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);
like image 8
Elliott Frisch Avatar answered Nov 19 '22 06:11

Elliott Frisch