Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number that is unique each time

Tags:

java

random

Hey I am trying to create a program that generates a random number that is only allowed to be used once. Sorry if that's confusing I'll try to explain. I want to have a program generate numbers from 1-100, but say if it generates 33, then for the rest of the number generation process 33 cannot be generated again, So I should end with exactly 100 different numbers. Any help is really appreciated, Thank you.

Here's my attempt so far

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())  ;
            }
        }
    }
}
like image 684
Brendan Zotto Avatar asked Dec 19 '22 10:12

Brendan Zotto


1 Answers

Precompute a List containing all the required numbers, then shuffle it and remove elements each time you need to generate a new number. Eg:

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);
like image 53
Jack Avatar answered Jan 06 '23 23:01

Jack