Showing posts with label How to generate random numbers. Show all posts
Showing posts with label How to generate random numbers. Show all posts

How to generate multiple random integers in C++

You may have already learned how to generate random numbers using the rand(), srand() and time() functions:
https://progressivecpp.blogspot.com/2020/03/How-to-generate-random-numbers-Cpp-rand-srand-time.htmll

However, try applying a LOOPING and generating several times, in consecutive ways: it will be a problem, it will comes out the same number!

The solution with rand() is recommended if you are going to generate a random number only once, or with spacing of several seconds, between one generation and another.

To generate several numbers in a row, up to millions, we recommend using the random library, as follows:
#include <iostream>
#include <iomanip>
#include <random>
using namespace std;

int gen_number()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);

    return dis(gen);
}

int main()
{
    int aux;

    for(aux=0 ; aux<1000 ; aux++)
        cout<<gen_number()<<endl;

    return 0;
}
Note that it will generate numbers from 1 to 6 (simulating a dice roll, for example).
If you want other intervals, just change (1.6) to a range you want.

Reference: https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

Random numbers in C++: How to generate with rand(), srand() and time() functions

In this tutorial from our Progressive C++ course, we will learn how to generate numbers or any range of random, or random, numbers.

Random numbers with the function rand()

In many programs, it will be necessary to have random numbers.

For example, to draw a song in your player, to choose a random video from Youtube, to make a draw with Instagram followers, to choose a location on the game map that you created in C++, and etc. etc. etc.

The first way we have to do this is by using the rand() function, from the cstdlib library.
It will generate a number between 0 and the constant RAND_MAX.

First, let's look at the value of this RAND_MAX, which can vary from machine to machine:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout<<"Interval: 0 - "<<RAND_MAX<<endl;

    return 0;
}
The result of the previous program on my machine was 2147483647.
And on your PC?

Now let's generate a random number:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout<<rand()<<endl;

    return 0;
}
Now let's generate 6 random numbers:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int i;

    for(i=0 ; i<6 ; i++)
        cout<<rand()<<" ";

    return 0;
}
Did you notice anything?
Close your program. Open it again ... did you notice anything?

Yes, the random numbers are repeated! But, calm down, let's see how to solve this.

The function srand() and random seeds

In truth, there is no purely random number. There is a whole science, and studies and more studies and research on top of that.

Basically, some rule will have to be used to generate these numbers, which are actually pseudo-random. However, there is a way around this.

It is by providing numbers, ourselves, for C++ to take these values and generate different numbers from them. For this, we will use the srand() function, which accepts an integer as a parameter (an unsigned int, actually).

For example, do:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    srand(2112);
    cout<<rand()<<endl;

    return 0;
}
See that now the value of the rand() has changed, it was no longer those numbers repeating.

Now it will generate other 'random' ones, as we supply 2112 as seed. But if you close and open the program, you will notice that the same 'random' values will appear.

Try this now:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int i;

    for(i=1 ; i<=10 ; i++){
        srand(i);
        cout<<rand()<<endl;
    }

    return 0;
}
Now everything was different, because at each iteration the seed that fed the srand() was different.
But even so, if you close and open it again, everything will be the same again, damn...

Function time() from library ctime

See how brilliant programmers are.

There is a function, from the ctime library, the time(), which when invoked returns the number of seconds since 00:00 on January 1, 1970. The trick is to use it as a seed generator, for srand().

Look:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    unsigned seed = time(0);

    srand(seed);
    cout<<rand()<<endl;

    return 0;
}
Open and close ... several times ... always different now, the number drawn!
After all, every second the team's return (0) is different, generating different seeds for srand(), which changes the rand (), which gives us different random numbers! PIMBA!

Choosing value ranges
1443561896
1944127442
107792574
1300800110
...
What kind of values are these? Very large ... we will rarely want to generate numbers that big. We want random ones that are 0 or 1 ... from 1 to 6 ... from 1 to 60 ... between 0 and 100 ... something like that, do you agree?

This is easily resolved with the rest of the division operator: %

For example, for:

Generate random ones that are 0 or 1
Just do: rand ()% 2
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    unsigned seed = time(0);

    srand(seed);
    cout<<rand()%2<<endl;

    return 0;
} 
  • Generate random from 1 to 10
Using rand ()%10: it will generate the numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9
So, just add 1, and we have numbers from 1 to 10.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    unsigned seed = time(0);

    srand(seed);
    cout<<1+rand()%10<<endl;

    return 0;
}


Nice, right?

List of C++ Function Exercises (Resolved and Commented)

We have reached the end of another section of our C++ course, about functions.
In the exercises below, you should use all your knowledge learned so far, such as the basics, loops, loopings, conditional tests and, of course, function.

Use and use again the functions. Create many functions.
Each function must do a single thing, in the simplest and most direct way possible.

Make them easily coupled, that is, you should receive and return information whenever possible. This allows you to use your function codes later.

Remember: a large program is nothing more than a series of small programs.
Your functions should be these little programs, making specific functionalities, ok?

Function Exercises in C++

01. Create a program that receives two smaller sides of a right triangle and a function returns the value of the hypotenuse.

02. Create a program that receives the three sides of a triangle, passes these values ​​to a function that says whether that triangle exists or not (due to the condition of the triangle's existence, each side must be greater than the subtraction module of the other two sides and must be less than the sum of the other two sides)

03. Make a program that asks the user for a positive integer 'n' and print a square of side 'n' filled with hashtags. For example, for n = 4, it should appear on the screen:

####
####
####
####

04. Program a software that receives three numbers, stops for a function and it returns the largest one. Make another function that receives the same numbers and returns the smallest one.


05. A number is said to be perfect when it is equal to the sum of its divisors.
For example, six is ​​perfect, because: 6 = 1 + 2 + 3
Programs a software that asks the user for a number and tells them if it is perfect or not.

06. Create software that receives a number from the user, passes that value to a function and it returns that number written in reverse. For example, you gave the value 1234, so it will return 4321. Tip: first, create a function that counts how many digits a number has.

07. Make a program to toss a coin. When we call a function, it must return heads or tails. In another function, make 'n' coin tosses, 'n' is the amount the user wants, and show the percentage of times he has heads and tails. If you flip the coin 10, 100, 1000, a million times ... what tends to happen?

08. Create data in C++. Roll the dice: that is, a function must draw a random number from 1 to 6. Now, make the previous die roll 100 times, a thousand times and 1 million times. Each time it runs, you must store the value it provided, at the end, you show how many times each number was drawn. Does it match the results of the statistic?

09. Create an odds and even game. You must choose 0 for even or 1 for odd, then provide a number. The computer generates a number from 0 to 10, adds the values ​​and says who won, besides showing the score and asking if you want to play another round.
How to program odds or even in C++

10. Like the odd or even game, create the Rock, Paper or Scissors game, in C ++.

11. Create a game where the computer draws a number from 1 to 10, and you try to guess what it is.

12.  Are we really going to make a cool and interesting game? Make the computer draw a number from 1 to 100. Each time you kick, it should tell you if you kicked below the real value, above or if you got it right. At the end, it tells you the number of attempts you had and whether or not you hit the record. Oh, at the end of each round, the program asks if you want to play again or not, displaying the current record.
Guess the number