Generate Random Numbers Within Range in C Without Repetition

Generate Random Numbers Within Range in C Without Repetition

Many times we need to perform tasks randomly to full fill our program(e.g game,quiz etc.) goals but repetition of same number again and again fails our program and feels irritating to our users. So, today we will help you to create a simple C/C++ program which will generate random numbers within given range and we will make sure no number will repeats itself again. Let's get started!
Generate Random Numbers in C and C++

Generating Random Numbers In C or C++

If you checked most basic random number generation program in C, you might have some knowledge about rand() function in C which is used to generate random numbers.

Why I said that most basic?
Because, rand() function works very well but after running that program again and again you can identify that its generating the same series or number all the time.

So how to fix?
To fix this common issue we usually need to seed our rand function using srand() function. And this is how srand function is used to generate different number all the time:
srand(time(NULL));

So now we know how to generate random number and how to fix its common problem. Now we are all set to define our range and actually generate random number in that range which will not repeat itself again.

C Program To Generate Random Number Within Range Without Repetition

#include <stdio.h>
#define N1 2
#define N2 10

void main(){
    int len = N2-N1+1,i , r , temp;
    int num[len];

    //Fill array with desired numbers
    for( temp=0,i=N1; temp<len; i++,temp++ )
        num[temp] = i;

    srand( time(NULL) );  //seed rand()

    //Fisher–Yates shuffle algorithm
    for( i=len-1; i>0; i-- ){
        r = rand()%i;   //pop random number
        //swaping using temp
        temp = num[i];
        num[i] = num[r];
        num[r] = temp;
    }

    /*Random Numbers b/w N1-N2 are stored in Array num*/

    //print the array
    for( i=0; i<len; i++ )
        printf("%d\n",num[i]);
}

Output:
C Program To Generate Random Number Within Range Without Repetition

Program Explanation

Firstly we defined our range at the top using #define N1 and N2 where N1 and N2 are our lower and upper bound respectively.

Skipping other variables deceleration directly coming to variable len , this is used to calculate the size of array required to store all the number within range.

After declaring array and other variables we have to fill/assign all the desired numbers into our array num.
Which is easily done using a for loop to generate numbers between N1 to N2 and variable temp is used as index of array num from 0 to len.

srand is used to generate unique solution every time as explained earlier.

Shuffle: Their are various ways to generate unique random numbers between range but above program in inspired by Fisher–Yates shuffle. We will explain more about Fisher–Yates algorithm soon so keep calm and wait for proper explanation.

After shuffle our array num is set to print/use numbers which are between our range and since are shuffled they act as random and finally full fill our objective.


C++ Program To Generate Random Number Within Range Without Repetition

Little changes in above code and same program will work perfectly in C++.

#include <iostream>
#include <stdlib.h>
#include <time.h>
#define N1 5
#define N2 10
using namespace std;

main(){
    int len = N2-N1+1 , i , r , temp;
    int num[len];

    for( temp=0,i=N1; temp<len; i++,temp++ )
        num[temp] = i;

    srand( time(NULL) );  //seed rand()

    //Fisher–Yates shuffle algorithm
    for( i=len-1; i>0; i-- ){
        r = rand()%i;
        temp = num[i];
        num[i] = num[r];
        num[r] = temp;
    }

    for( i=0; i<len; i++ )
        cout << num[i] << endl;
}

Conclusion:
So, now you know the easiest way to generate random numbers within range and also without repeating. Hope you enjoyed our programming article after a long time. Please share if you liked this or any other post.

1 Comment. Leave new

ACH Betting on Horse Racing - JT Hub
An ACH Betting on Horse Racing from JT-BET is 성남 출장마사지 the best 포천 출장안마 way to show 남원 출장안마 off what makes it a great 창원 출장안마 place to watch. Bet On Horse Racing, 경주 출장안마 TV and the Best Online

Reply

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.