Matt
Matt

Reputation: 147

C: create random numbers from a range that are all different

For example, I have these 3 variables:

N = 5;
int r1 = rand() % N;
int r2 = rand() % N;
int r3 = rand() % N;

How can I get 3 different numbers in that range that are not the same? I tried with this code:

do{
  int r1 = rand() % N;
  int r2 = rand() % N;
  int r3 = rand() % N;
}while((r1 == r2) && (r1==r3) && (r2==r3));

but it doesn't work. Sometimes one or two numbers are the same (ex: 1, 1, 4). But I need them all to be different. How can I do this?

Upvotes: 1

Views: 79

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

This code will pick 3 different numbers in the range 0..4. It works by creating an array of available numbers, as one each is picked it is removed from the list. This removes the inefficiency of repeatedly attempting to fulfil the condition that all are different - which might NEVER happen with a true RNG!

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

#define RANGE   5                   // how many different numbers
#define PICK    3                   // how many to pick

int main(void) {
    int pool[RANGE];
    int size, n, i;
    srand((unsigned)time(NULL));
    for (size=0; size<RANGE; size++) {
        pool[size] = size;          // create number pool
    }

    // pick different numbers
    for(i=0; i<PICK; i++) {
        n = rand() % size;          // random array index
        printf("%d ", pool[n]);     // select number from pool
        pool[n] = pool[--size];     // remove from pool
    }
    printf("\n");
    return 0;
}

Upvotes: 4

Related Questions