Here is the description of the the problem
Given an integer N, write a function which returns an integer array of size N, containing the numbers from 1 to N in a random order. Each number from 1 to N must appear once and must not repeat.
For example: if you are given the number 4, your output must generate something like 4213, 2413, 3124, etc.
Invalid outputs would be 1123, 4444, 244.
Any ideas to solve the problem?
Yes it's home work. I just finished writing the algorithm in java, but using Fisher-Yates shuffle seems to be much more efficient. Thank you people. Below is my version of the algorithm.
Collection<Integer> generateNumbers(int n) {
Collection<Integer> numbers = new HashSet<Integer>();
Random rand = new Random();
int max = 0;
int min = 0;
for(int i=0;i<n;i++){
max=(max*10)+n;
min=(min*10)+1;
}
while(numbers.size()<n){
int random = rand.nextInt(max-min+1)+min;
int temp = random;
boolean good = true;
Set<Integer> digits = new HashSet<Integer>();
while(temp>0 && good){
int reminder = temp%10;
if(reminder > 0 && reminder <= n ){
digits.add(reminder);
}else
good = false;
temp/=10;
}
if(good && digits.size() == n)
numbers.add(random);
}
return numbers;
}
Here is a hint: look up what a Fisher-Yates shuffle is.
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