-1

I'm trying to write a program that can place numbers from 1 to 20 in a random and non-repetitive way to a 20 element array.

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
 int i,j,A[20],flag;
    srand(time(NULL)); 

    for(i=0; i<20; i++){
        flag=1;
        A[i]=1+rand()%19;
       for(j=0;j<20;j++){

           if(A[i]==A[j]){
            flag=0;
             break;
           }

        }
        if(flag=0){
            continue;
        }
        else
        printf("%d ",A[i]);
   }
    return 0;
}

It gives repeated output.

5
  • 3
    See Fisher–Yates shuffle. Commented Dec 7, 2018 at 21:25
  • rand() does not guarantee non-repetition. Commented Dec 7, 2018 at 21:25
  • random the index 0..19 instead of the value, then swap with another random index 0..19 repeat X times Commented Dec 7, 2018 at 21:28
  • @Anders I'm not sure your algorithm is unbiased... and most importantly, how big should X be to get a "good" random permutation? Just use Yates shuffle, it is provable and has optimal complexity - you need exactly N-1 extractions/swaps to get a provably random, uniformly chosen permutation. Commented Dec 7, 2018 at 21:34
  • Just reinitialize the time each time i mean inside the loop Commented Dec 8, 2018 at 3:46

1 Answer 1

2

You could place the numbers from 1 to 20 in the array and then scrumble the array with an algorithm like this one

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.