Dec 15, 2011

Without repeating random numbers in C++


The need to generate random numbers without a recurrence . It may be useful for various things such as randomly ordered list items, forms random groups, shuffling cards, etc.. So algorithm would be something like:
  1. Create an array and leave it empty.
  2. Get a random number.
  3. Check if that number exists in the array. If yes, return to step 2. If not, save the number in the matrix.
So the program is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<cstdlib> # Include 
# include <ctime> 
<iostream> # include 
using  namespace std ;
 
bool checkRep ( int n, int num [ ] ) 
{ 
    for ( int i = 0 ; i < 10 ; i + + ) 
        if ( n == num [ i ] ) 
            return  true ; 
    return  false ; 
}
 
int main ( ) 
{ 
    srand ( time ( NULL ) ) ; 
    int n, num [ 10 ] ; 
    for ( int i = 0 ; i < 10 ; i + + ) 
    { 
        do 
            n =  1  +  rand ( )  %  10 , 
        while ( checkRep ( n, num ) ) ; 
        num [ i ]  = n ; 
        court  << num [ i ]  <<  "" ; 
    } 
}
First of all, <cstdlib> is the correct way to include the library in c + + <stdlib.h>, same with <ctime>.
You see, we use a bool function ( which returns true or false ) to check if the random number already exists in our matrix. If any of the numbers is equal to our random number n , the function returns true , so that the cycle do-while since we call the function will be repeated again until the function returnsfalse .
When it gets out of do-while loop, we keep our n in place of the corresponding matrix, as shown on the screen and continue to the next position in the array.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes