rand( )

iostream's Avatar, Join Date: Jun 2009
Newbie Member
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

Last edited by SaswatPadhi; 21Jun2009 at 17:58.. Reason: Code blocks
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
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.
0
iostream's Avatar, Join Date: Jun 2009
Newbie Member
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.
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
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
0
iostream's Avatar, Join Date: Jun 2009
Newbie Member
thank you !
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
My pleasure !!