Mayank
Mayank

Reputation: 21

Generating list of random numbers without duplication using C?

I was making a puzzle game and i want to generate a list of random numbers between some limit. I have already used rand and srand function but it gives me duplicate value also. I want to generate a random list without duplication how would i do that?

Upvotes: 2

Views: 7963

Answers (5)

salva
salva

Reputation: 10244

This method results appropriate when the limit is high and you only want to generate a few random numbers.

#!/usr/bin/perl

($top, $n) = @ARGV; # generate $n integer numbers in [0, $top)

$last = -1;
for $i (0 .. $n-1) {
    $range = $top - $n + $i - $last;
    $r = 1 - rand(1.0)**(1 / ($n - $i));
    $last += int($r * $range + 1);
    print "$last ($r)\n";
}

Note that the numbers are generated in ascending order, but you can shuffle then afterwards.

Upvotes: 0

David Gelhar
David Gelhar

Reputation: 27900

The usual approach for this is something like:

  populate an array source_array of size <n> with numbers from 0 to n-1

  while n > 0
  use rand to generate a random number x in the range 0..n-1

  add source_array[x] to the result list

  source_array[x] = source_array[n-1]; // replace number just used with last value

  --n; // next time, one less number

Upvotes: 9

T I
T I

Reputation: 9933

I'll presume you are using an array to store the numbers, you could use something like this inArray() function and use it with a do ... while loop which would generate a random number until it generates one that is not in the array

Edit: w00te's comment links to this answer which I believe is better then my method and definitely worth a read. This is also what David Gelhar is briefly suggesting.

Upvotes: 0

Bruno Alano
Bruno Alano

Reputation: 643

You can do this:

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

#define MAX_NUMBER_VALUE 60
#define HOW_MANY_NUMBERS 10

int main ( void )
{
    int numbers[HOW_MANY_NUMBERS];
    int counter = 0;
    while ( counter < HOW_MANY_NUMBERS)
    {
        int tempRandom = rand ( MAX_NUMBER_VALUE + 1 );
        int check = 0;
        while ( check <= counter )
        {
            if ( number[counter] == number[check] )
                tempRandom = rand ( MAX_NUMBER_VALUE + 1 );
        }
        printf("Random number #%d - Value: %d", counter, tempRandom);
    }
}

You need perform this, but it works.

Upvotes: -1

Adel Boutros
Adel Boutros

Reputation: 10285

To avoid duplication, you could store all generated numbers in a list and on each iteration, check if the number was already generated; If yes, regenerate, if not add it to the list and show it.

Upvotes: -1

Related Questions