I want to generate four random numbers in the range of 0 to 9. It's easy to generate four random numbers with Java Random class.
Random random = new Random();
int numbers[] = new int[4];
for(int i=0;i<4;i++){
numbers[i] = random.nextInt(10);
}
With this, I can get an array of four numbers easily like, 9369, 4702 etc. In this case there may be possibility of a number to be repeated in four numbers and I don't want such repeat in numbers.
Here, I want to get all four digit in above array to be unique so that I can get output like 9543, 1234 etc.
For this, I have thought following way.
Is there any better way than above method so that I can get four unique random numbers easily and quickly ?
Any kind of suggestion is appreciated.
You can use Collections.shuffle
:
// generate a List that contains the numbers 0 to 9
List<Integer> digits = IntStream.range(0,10).boxed().collect(Collectors.toList());
// shuffle the List
Collections.shuffle (digits);
// take the first 4 elements of the List
int numbers[] = new int[4];
for(int i=0;i<4;i++){
numbers[i] = digits.get(i);
}
You can use Set
for that, the idea is to generate your random number then put it in a set and keep doing this until you have 4 elements in your set, when done you will have 4 unique random numbers stored in your set
Set<Integer> randomSet = new HashSet<>();
while(randomSet.size() <4)
randomSet.add //add your generated random number
If you can create a fast function f that maps the natural numbers to the set of numbers which fulfill your requirement, you can generate just one random number. Your run time is then bounded by f. Provided you can create a reasonably fast f, this is the most efficient way to do it.
The simplest solution would be to put all the numbers which satisfy your criterion in an array and create a random number as an index into that array. -> O(1)
As you see, there are a many ways to reach your goal. Here is my proposal
Random random = new Random();
// prepare all valid digits
List<Integer> from = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
// take set in an random order
int numbers[] = new int[4];
for(int i = 0; i < numbers.length; i++){
numbers[i] = from.remove (random.nextInt (from.size()));
}
for (int num : numbers) {
System.out.println(num); // when you prefer this
}
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