Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help needed for writing an algorithm

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?

like image 451
Srini Kandula Avatar asked Apr 09 '26 06:04

Srini Kandula


2 Answers

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;
}
like image 103
Srini Kandula Avatar answered Apr 11 '26 18:04

Srini Kandula


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

like image 43
Svante Avatar answered Apr 11 '26 18:04

Svante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!