How would i prevent duplicating numbers from random numbers. I need to generate 5 numbers between 1 and 9 that are each different. I would often get same numbers like 23334, how can i prevent that? Any help would be great!
int num2 = (int) Math.round((Math.random()*9) +1);
int num1 = (int) Math.round((Math.random()*9) +1);
int num5 = (int) Math.round((Math.random()*9) +1);
int num3 = (int) Math.round((Math.random()*9) +1);
int num4 = (int) Math.round((Math.random()*9) +1);
Floyd's subset selection algorithm is designed to do exactly what you want, and is extremely efficient even for large sets. Selecting
m
items from a set ofn
isO(m)
average running time, independent ofn
. Here's a Java implementation.After the set is filled you have 5 unique random numbers.
UPDATE: just to illustrate Jared Burrows' comment
Remove one element by index from the above generated random number. And add the removed element to a array which to be returned as a results
One option is to use shuffle algorithm (e.g. Fisher-Yates shuffle ) to generate random sequence from 1 to 9, then take first 5 numbers of the sequence
Further explanation on StackOverflow: https://stackoverflow.com/a/196065/950427
I suppose you would need to store the ones that have been generated into an array and compare the new random number to the list to ensure it is unique.
I notice you did not use an array in your example, so in case you do not know how to use them yet, you could also make 5 variables.
And you could continue making while statements like that. But if you are supposed to know about arrays, you should definitely be using one to store the numbers.
One possible approach to this problem can be divide & conquer. Step of following describes the approach:
Benefit: benefit of this approach is that, in worst case, it's runtime will be O(x), where x is the number of random number required. The best case scenarion is also o(x), as i have to find at least n number of random. These two comprise average case to θ(x) complexity.