-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.

dbush
  • 205,898
  • 23
  • 218
  • 273
XoReNiC
  • 1
  • 5
  • 3
    See [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). – dbush Dec 07 '18 at 21:25
  • `rand()` does not guarantee non-repetition. – Reinderien Dec 07 '18 at 21:25
  • random the index 0..19 instead of the value, then swap with another random index 0..19 repeat X times – AndersK Dec 07 '18 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. – Matteo Italia Dec 07 '18 at 21:34
  • Just reinitialize the time each time i mean inside the loop – Fuel Dec 08 '18 at 03:46

1 Answers1

2

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