views:

173

answers:

3

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.

  • What is the running time of your algorithm?
  • Can your algorithm be improved?

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?

+3  A: 

Here is a hint: look up what a Fisher-Yates shuffle is.

Svante
+3  A: 

What you're doing is shuffling an integer array.

Here's an explanation of the Knuth shuffle.

Gilbert Le Blanc
+4  A: 

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;
}
Srini Kandula
that thing you're doing with min and max seems unnecessary
Ben Schwehn
Isn't a `HashSet` unordered? Doesn't this defeat the purpose?
Svante
@Ben: You are right, I missed a minor part of the actual question. Thanks.
Srini Kandula
@Svante: I don't care what the order is, I need to make sure there is no duplicates. What do you think is a better option?
Srini Kandula
The problem description says "random order". The "order" of things in a HashSet is not random, but predetermined by the hash implementation; you should treat this order as nonexistent, which is not the same as "random" at all. You should use a collection with a defined order, e.g. ArraySet. Actually, you should just use an array, put the numbers in in order, and finally do an unbiased shuffle.
Svante