## Python || Custom Random Number Generator Class MyRNG

The following is sample code for a simple random number generator class. This random number generator is based on the Park & Miller paper “Random Number Generators: Good Ones Are Hard To Find.

This class has three functions. The constructor initializes data members “m_min” and “m_max” which stores the minimum and maximum range of values in which the random numbers will generate.

The “Seed()” function stores the value of the current seed within the class, and the “Next()” function returns a random number to the caller using an algorithm based on the Park & Miller paper listed in the paragraph above. Each time the “Next()” function is called, a new random number is generated and returned to the caller.

``` MyRNG.py - Custom Random Number Generator Python # ============================================================================= # Author: K Perkins # Date: Aug 6, 2013 # Taken From: http://programmingnotes.org/ # File: MyRNG.py # Description: This is the MyRNG.py module which contains the class # declaration for the random number generator. This module recieves a # seed, minimum, and maximum number and generates a random number using # the "Next()" function. Each time the "Next()" function is called, a new # random number is generated and returned to the caller # ============================================================================= import math, time class MyRNG: # MyRNG class. This is the class declaration for the random number # generator. The constructor initializes data members "m_min" and # "m_max" which stores the minimum and maximum range of values in which # the random numbers will generate. There is another variable named "m_seed" # which is initialized using the method Seed(), and stores the value of the # current seed within the class. Using the obtained values from above, the # "Next()" method returns a random number to the caller using an algorithm # based on the Park & Miller paper "RANDOM NUMBER GENERATORS: GOOD ONES ARE # HARD TO FIND" def __init__(self, low = 0, high = 0): # The constructor initializes data members "m_min" and "m_max" if(low < 2): low = 2 if(high < 2): high = 9223372036854775807 self.m_min = low self.m_max = high self.m_seed = time.time() def Seed(self, seed): # Seed the generator with 'seed' self.m_seed = seed def Next(self): # Return the next random number using an algorithm based on the # Park & Miller paper "RANDOM NUMBER GENERATORS: GOOD ONES ARE # HARD TO FIND" a = self.m_min m = self.m_max q = math.trunc(m / a) r = m % a hi = self.m_seed / q lo = self.m_seed % q x = (a * lo) - (r * hi) if(x < a): x += a self.m_seed = x self.m_seed %= m # ensure that the random number is not less # than the minimum number within the user specified range if(self.m_seed < a): self.m_seed += a return int(self.m_seed) def test(): # Simple test function to see if the functionality of my class # is there and works random = MyRNG(7, 1987) random.Seed(806189064) for x in range(15): print("%d, " %(random.Next()), end = "") if __name__ == '__main__': test() # http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 # =============================================================================#   Author:  K Perkins#   Date:   Aug 6, 2013#   Taken From: http://programmingnotes.org/#   File: MyRNG.py#   Description: This is the MyRNG.py module which contains the class#      declaration for the random number generator. This module recieves a#      seed, minimum, and maximum number and generates a random number using#      the "Next()" function. Each time the "Next()" function is called, a new#      random number is generated and returned to the caller# =============================================================================import math, time class MyRNG:#  MyRNG class. This is the class declaration for the random number#     generator. The constructor initializes data members "m_min" and#     "m_max" which stores the minimum and maximum range of values in which#     the random numbers will generate. There is another variable named "m_seed"#     which is initialized using the method Seed(), and stores the value of the#     current seed within the class. Using the obtained values from above, the#     "Next()" method returns a random number to the caller using an algorithm#     based on the Park & Miller paper "RANDOM NUMBER GENERATORS: GOOD ONES ARE#     HARD TO FIND"    def __init__(self, low = 0, high = 0):    #     The constructor initializes data members "m_min" and "m_max"        if(low < 2):            low = 2        if(high < 2):            high = 9223372036854775807        self.m_min = low        self.m_max = high        self.m_seed = time.time()     def Seed(self, seed):    #  Seed the generator with 'seed'        self.m_seed = seed     def Next(self):    #     Return the next random number using an algorithm based on the    #        Park & Miller paper "RANDOM NUMBER GENERATORS: GOOD ONES ARE    #        HARD TO FIND"        a = self.m_min        m = self.m_max        q = math.trunc(m / a)        r = m % a         hi = self.m_seed / q        lo = self.m_seed % q        x = (a * lo) - (r * hi)         if(x < a):           x += a         self.m_seed = x        self.m_seed %= m         # ensure that the random number is not less        # than the minimum number within the user specified range        if(self.m_seed < a):            self.m_seed += a         return int(self.m_seed) def test():#  Simple test function to see if the functionality of my class#     is there and works     random = MyRNG(7, 1987)    random.Seed(806189064)    for x in range(15):        print("%d,  " %(random.Next()), end = "") if __name__ == '__main__':    test()# http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above class is very simple to use. A sample function demonstrating its use is provided on line #64 in the above code snippet.

After running the code, the following is sample output:

SAMPLE OUTPUT:

``` 1037, 1296, 1123, 1900, 1375, 1676, 1798, 662, 664, 674, 746, 1249, 793, 1578, 1112, ```

## Java || Random Number Guessing Game Using Random & Do/While Loop

This is a simple guessing game, which demonstrates the use of the “Random” class to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will check to see if the user obtained number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```The "Random" Class Do/While Loop How To get Character Input Custom Setw/Setfill In Java ```

``` I'm Thinking of a Number Between 1 and 1000... Java // ============================================================================ // Author: Kenneth Perkins // Date: Nov 19, 2012 // Taken From: http://programmingnotes.org/ // File: GuessingGame.java // Description: Demonstrates a simple random number guessing game // ============================================================================ import java.util.*; public class GuessingGame { // global variable declarations static Scanner cin = new Scanner(System.in); static Random rand = new Random(); // this is the call to the "Random" class public static void main(String[] args) { // declare & initialize variables char playAgain = 'y'; int userInput = 0; int numGuesses = 0; int randomNumber = rand.nextInt(1000)+1; // ^ get a number from the random generator in the range of 1 - 1000 System.out.println("Welcome to My Programming Notes' Java Program.\n"); // display directions to user System.out.println("I'm thinking of a number between 1 and 1000. Go " + "ahead and make your first guess.\n"); do { // this is the start of the do/while loop System.out.print(">> "); // get data from user userInput = cin.nextInt(); System.out.println(""); // increments the 'numGuesses' variable each time the user // gets the guess wrong ++numGuesses; // if user guess is too high, do this code if (userInput > randomNumber) { System.out.println("Too high! Think lower."); } // if user guess is too low, do this code else if (userInput < randomNumber) { System.out.println("Too low! Think higher."); } // if user guess is correct, do this code else { // display data to user, prompt if user wants to play again System.out.print("You got it, and it only took you " +numGuesses+" trys!\nWould you like to play again (y/n)? "); playAgain = cin.next().charAt(0); // if user wants to play again then re initialize the variables if (playAgain == 'y'|| playAgain == 'Y') { // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 60, '-'); numGuesses = 0; System.out.println("\n\nMake a guess (between 1-1000):\n"); // generate a new random number for the user to try & guess randomNumber = rand.nextInt(1000)+1; } } System.out.println(""); } while (playAgain == 'y' || playAgain == 'Y'); // ^ do/while loop ends when user doesnt select 'Y' // display data to user System.out.println("Thanks for playing!!"); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 // ============================================================================//    Author: Kenneth Perkins//    Date:   Nov 19, 2012//    Taken From: http://programmingnotes.org///    File:  GuessingGame.java//    Description: Demonstrates a simple random number guessing game// ============================================================================import java.util.*; public class GuessingGame{    // global variable declarations    static Scanner cin = new Scanner(System.in);    static Random rand = new Random(); // this is the call to the "Random" class     public static void main(String[] args)    {        // declare & initialize variables        char playAgain = 'y';        int userInput = 0;        int numGuesses = 0;        int randomNumber = rand.nextInt(1000)+1;        // ^ get a number from the random generator in the range of 1 - 1000         System.out.println("Welcome to My Programming Notes' Java Program.\n");         // display directions to user        System.out.println("I'm thinking of a number between 1 and 1000. Go " +                "ahead and make your first guess.\n");         do { // this is the start of the do/while loop             System.out.print(">> ");            // get data from user            userInput = cin.nextInt();            System.out.println("");             // increments the 'numGuesses' variable each time the user            // gets the guess wrong            ++numGuesses;             // if user guess is too high, do this code            if (userInput > randomNumber)            {                System.out.println("Too high! Think lower.");            }             // if user guess is too low, do this code            else if (userInput < randomNumber)            {                System.out.println("Too low! Think higher.");            }             // if user guess is correct, do this code            else            {    // display data to user, prompt if user wants to play again                System.out.print("You got it, and it only took you "                    +numGuesses+" trys!\nWould you like to play again (y/n)? ");                playAgain = cin.next().charAt(0);                 // if user wants to play again then re initialize the variables                if (playAgain == 'y'|| playAgain == 'Y')                {                    // creates a line seperator if user wants to enter new data                    System.out.println("");                    setwRF("", 60, '-');                     numGuesses = 0;                    System.out.println("\n\nMake a guess (between 1-1000):\n");                    // generate a new random number for the user to try & guess                    randomNumber = rand.nextInt(1000)+1;                }            }            System.out.println("");        } while (playAgain == 'y' || playAgain == 'Y');        // ^ do/while loop ends when user doesnt select 'Y'        // display data to user        System.out.println("Thanks for playing!!");    }// end of main     public static void setwRF(String str, int width, char fill)    {        System.out.print(str);        for (int x = str.length(); x < width; ++x)        {            System.out.print(fill);        }    }// end of setwRF}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

`Welcome to My Programming Notes' Java Program.`

``` I'm thinking of a number between 1 and 1000. Go ahead and make your first guess. >> 900 Too high! Think lower. >> 300 Too high! Think lower. >> 100 Too low! Think higher. >> 200 Too low! Think higher. >> 350 You got it, and it only took you 5 trys! Would you like to play again (y/n)? y ------------------------------------------------------------ Make a guess (between 1-1000): >> 300 Too low! Think higher. >> 600 Too high! Think lower. >> 500 Too high! Think lower. >> 400 You got it, and it only took you 4 trys! Would you like to play again (y/n)? n ```

`Thanks for playing!!`

## C++ || Random Number Guessing Game Using Srand, Rand, & Do/While Loop

This is a simple guessing game, which demonstrates the use of srand and rand to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will then check to see if the user inputted number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Srand Rand Modulus Ctime Do/While Loop```

NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.

``` I'm Thinking of a Number Between 1 and 1000... C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 20, 2012 // Taken From: http://programmingnotes.org/ // File: guessingGame.cpp // Description: Demonstrates a simple random number guessing game // ============================================================================ #include <iostream> #include <ctime> #include <iomanip> using namespace std; int main() { // declare & initialize variables char playAgain = 'y'; int userInput = 0; int numGuesses = 0; // Seed the random number generator with the current time so // the numbers will be different every time the program runs srand(time(NULL)); int randomNumber = rand() % 1000+1; // display directions to user cout << "I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.\n\n"; do{ // this is the start of the do/while loop // get data from user cin >> userInput; // increments the 'numGuesses' variable each time the user // gets the guess wrong ++numGuesses; // if user guess is too high, do this code if(userInput > randomNumber) { cout << "Too high! Think lower.\n"; } // if user guess is too low, do this code else if(userInput < randomNumber) { cout << "Too low! Think higher.\n"; } // if user guess is correct, do this code else { // display data to user, prompt if user wants to play again cout << "You got it, and it only took you " << numGuesses <<" trys!\nWould you like to play again (y/n)? "; cin >> playAgain; // if user wants to play again then re initialize the variables if(playAgain == 'y'|| playAgain =='Y') { // creates a line seperator if user wants to enter new data cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; numGuesses = 0; cout << "\n\nMake a guess (between 1-1000):\n\n"; // generate a new random number for the user to try & guess randomNumber = rand() % 1000+1; } } }while(playAgain =='y' || playAgain =='Y'); // ^ do/while loop ends when user doesnt select 'Y' // display data to user cout<<"\n\nThanks for playing!!"<<endl; return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 20, 2012//    Taken From: http://programmingnotes.org///    File:  guessingGame.cpp//    Description: Demonstrates a simple random number guessing game// ============================================================================#include <iostream>#include <ctime>#include <iomanip>using namespace std; int main() { // declare & initialize variables char playAgain = 'y'; int userInput = 0; int numGuesses = 0; // Seed the random number generator with the current time so     // the numbers will be different every time the program runs srand(time(NULL)); int randomNumber = rand() % 1000+1;  // display directions to user cout << "I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.\n\n"; do{ // this is the start of the do/while loop  // get data from user cin >> userInput; // increments the 'numGuesses' variable each time the user // gets the guess wrong ++numGuesses; // if user guess is too high, do this code if(userInput > randomNumber) { cout << "Too high! Think lower.\n"; }  // if user guess is too low, do this code else if(userInput < randomNumber) { cout << "Too low! Think higher.\n"; }  // if user guess is correct, do this code else {    // display data to user, prompt if user wants to play again cout << "You got it, and it only took you " << numGuesses         <<" trys!\nWould you like to play again (y/n)? "; cin >> playAgain;  // if user wants to play again then re initialize the variables if(playAgain == 'y'|| playAgain =='Y') { // creates a line seperator if user wants to enter new data cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl;  numGuesses = 0; cout << "\n\nMake a guess (between 1-1000):\n\n"; // generate a new random number for the user to try & guess randomNumber = rand() % 1000+1; } } }while(playAgain =='y' || playAgain =='Y');     // ^ do/while loop ends when user doesnt select 'Y'   // display data to user cout<<"\n\nThanks for playing!!"<<endl;          return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

`I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.`

``` 67 Too low! Think higher. 500 Too low! Think higher. 700 Too high! Think lower. 600 Too low! Think higher. 680 Too high! Think lower. 650 Too low! Think higher. 660 Too low! Think higher. 670 You got it, and it only took you 8 trys! Would you like to play again (y/n)? y ------------------------------------------------------------ Make a guess (between 1-1000): 500 Too low! Think higher. 600 Too low! Think higher. 700 Too low! Think higher. 900 Too high! Think lower. 800 Too high! Think lower. 760 Too high! Think lower. 740 Too high! Think lower. 720 Too high! Think lower. 700 Too low! Think higher. 710 Too high! Think lower. 705 Too high! Think lower. 701 Too low! Think higher. 702 Too low! Think higher. 703 Too low! Think higher. 704 You got it, and it only took you 15 trys! Would you like to play again (y/n)? n ```

`Thanks for playing!!`