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()) ;
}
}
}
}
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);
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