Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   rand( ) (http://www.go4expert.com/forums/rand-t18140/)

iostream 21Jun2009 15:32

rand( )
 
Code: C

#include <iostream>
 #include <vector>
 #include<conio.h>

 using namespace std;

 int main( )
 {
 const int DIFFERENT_NUMBERS = 10;

 // Prompt for and read number of games.
 int totalNumbers;
 cout << "How many numbers to generate?: ";
 cin >> totalNumbers;

 // Initialize the vector to zeros.
 vector <int> numbers( DIFFERENT_NUMBERS + 1,0 ) ; // shorthand for the following code
/* for( int i = 0; i < numbers.size( ) ; i++ )
 numbers[ i ] = 0; */


 // Generate the numbers.
 for( int j = 0; j < totalNumbers; j++ )
 numbers[ rand( ) % DIFFERENT_NUMBERS + 1 ]++ ;

 // Output the summary.
 for( int k = 1; k <= DIFFERENT_NUMBERS; k++ )
 cout << k << " occurs " << numbers[ k ]<< " time(s) \n";

getch();
 }


hello ,
I am having trouble understanding the program from (generate the numbers).
please explain it dissecting the code from there !


thnx

SaswatPadhi 21Jun2009 18:05

Re: rand( )
 
The program works this way :
(1) Creates a vector that stores the number of repetitions of the generated numbers. number[i] stores the number of times the integer i is generated.
(2) This loop basically generates the numbers and keeps track of repetitions :
Code: C

for( int j = 0; j < totalNumbers; j++ )
      // Increases the count for the generated number
      numbers[ rand( ) % DIFFERENT_NUMBERS + 1 ]++ ;

All numbers generated are within 1 to 10 (both inclusive).
(3) Output section simply shows how many times each number was generated.

iostream 22Jun2009 08:33

Re: rand( )
 
thnx, but can u please make me understand :

numbers[ rand( ) % DIFFERENT_NUMBERS + 1 ]++ ;

for example, the random no. chosen is 5 then wat r the next steps taken.

SaswatPadhi 22Jun2009 12:40

Re: rand( )
 
OK. Let the rand() return 2574.
As DIFFERENT_NUMBERS = 10, rand( ) % DIFFERENT_NUMBERS = 4.
So, rand( ) % DIFFERENT_NUMBERS + 1 = 4 + 1 = 5.

So, the statement finally becomes : numbers[5]++ i.e. the count of '5' increases by one.
This is repeated 'totalNumbers' times.

Let the user enter 'totalNumbers' as 7.
So, 7 random numbers are chosen within 1 ~ 10 : say - 1, 7, 8, 2, 3, 1, 7.
So, the numbers array will have the following content :
numbers[1] = 2
numbers[2] = 1
numbers[3] = 1
numbers[4] = 0
numbers[5] = 0
numbers[6] = 0
numbers[7] = 2
numbers[8] = 1
numbers[9] = 0
numbers[10] = 0

I hope it's clear now :)

iostream 22Jun2009 13:40

Re: rand( )
 
thank you ! :pleased::pleased::pleased:

SaswatPadhi 22Jun2009 17:58

Re: rand( )
 
My pleasure !! :)


All times are GMT +5.5. The time now is 07:41.