How to generate a random number that is unique every time

Hi, I am trying to create a program that generates a random number that is allowed to be used only once. Sorry if this is confusing, I will try to explain. I want the program to generate numbers from 1 to 100, but let's say if it generates 33, then for the rest of the process of generating the numbers, 33 cannot be created again, so I have to end up with exactly 100 different numbers. Any help really appreciated, thanks.

Here is my attempt

public class Seed {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a =0; 
        for (int i =0; i <20;i++) {
             a = (int) Math.ceil(10 * Math.random())  ;
            System.out.println(a);
            int x = a;
            System.out.println("This is x: " + x);

            if (x == a )
            {
                a = (int) Math.ceil(10 * Math.random())  ;
            }
        }
    }
}
+4
source share
1 answer

a List, , , . :

List<Integer> numbers = new ArrayList<Integer>(100);

for (int i = 0; i < 100; ++i)
  numbers.add(i);

Collections.shuffle(numbers);

int pick = numbers.remove(0);
int pick2 = numbers.remove(0);
+11

All Articles