how get random values?

i have these function for get a random values:
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <conio.h>
#include <string>
#include <windows.h>
#include <time.h>

using namespace std;

void GotoXY( int PosX, int PosY )
{
    COORD p = { (SHORT)PosX, (SHORT)PosY };
    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), p );
}

void Clear( int BackGroundColor=0, int ForeColor=1)
{
    string strComand="color " + to_string(BackGroundColor) + to_string(ForeColor);
    system(strComand.c_str() );
    system("cls");
}
int randpos(int ranmax=100)
{
    int r = rand() % ranmax +1;
    return r;
}

int main()
{
    //loop for draw text on screen on a random position
    while(1)
    {
        srand(time(NULL));//reset the random
        Clear(6,6);//clear the screen with a color using the system() function
        GotoXY(randpos(),randpos());//change cursor position using SetConsoleCursorPosition() function
        //and random values
        cout << "hello world!!!"; //draw the text
        if( GetKeyState(27) & 0x8000 ) break; //press ESC to exit
    };
    return 0;
}

but just seen the random function:
1
2
3
4
5
int randpos(int ranmax=100)
{
    int r = rand() % ranmax +1;
    return r;
}

these code works, but why the random values seems to be several times repeated?
call srand once, not in a loop.
You are currently calling srand(time(NULL)) every time that loop runs. By doing so, you're resetting your PRNG's seed to the current time every time that loop runs. Guess what happens when your loop runs several times a second?

-Albatross
better, but why the random max seems to be more used than others values?
seems that i found the error...
in function the max value is 100... but the standard window size is 120X30.... maybe that was the problem without notice
why the random max seems to be more used than others values?

It shouldn't be.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>

int randpos(int ranmax) {
    return std::rand() % ranmax + 1;
}

int main() {
    std::srand(std::time(nullptr));
    int a[101] {};
    for (int i = 0; i < 100000; ++i)
        ++a[randpos(100)];
    for (int i = 1; i <= 100; ++i)
        std::cout << std::setw(3) << i    << ' '
                  << std::setw(5) << a[i] << '\n';
}

Last edited on
Because rand() is awful. It's a bad random number generator. if you need good random numbers, don't use it.

https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Note: rand() % N is almost never going to be perfectly uniform, for statistical reasons, as well as rand() possibly being a poor implementation (FurryGuy's post). But I'm assuming this isn't necessarily what's going on here... because usually the non-uniformity isn't *too* much.

Cambalinho, can you provide actual data to back the claim that a particular value is the result much more often than other values? dutch's post shows that it provides (more or less) a "good enough" result.

Edit: Just saw this, for some reason
Cambalinho wrote:
in function the max value is 100... but the standard window size is 120X30.... maybe that was the problem without notice

I figured it was something like that going on, and not an issue with the RNG itself.
Last edited on
now seems to work more efficient...
PS: some functions use '/' instead '%'.. always use the '%', because it's more efficient...
thank you
Repeater: why random.h is better than rand() or srand()?
Last edited on
Fun fact: OpenBSD's rand is good enough to use for cryptography, and non-deterministic by default (making srand a no-op). Alright, fun fact over.

Cambalinho, if you have some spare time, you might want to read up on modern C++'s <random> header and how to use the stuff in it.
http://www.cplusplus.com/reference/random/uniform_int_distribution/#example

(Keep in mind that default_random_engine itself is not necessarily better than rand, but uniform_int_distribution is definitely better than using %).

-Albatross
the:
std::uniform_int_distribution<int> distribution(0,9);
means random values between 0 and 9?
Yep.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>
#include <random>
#include <chrono>

int randpos(int ranmax) {
    static std::default_random_engine eng(std::chrono::high_resolution_clock{}
                                          .now().time_since_epoch().count());
    return std::uniform_int_distribution<>(1, ranmax)(eng);
}

int main() {
    int a[101] {};
    for (int i = 0; i < 100000; ++i)
        ++a[randpos(100)];
    for (int i = 1; i <= 100; ++i)
        std::cout << std::setw(3) << i    << ' '
                  << std::setw(5) << a[i] << '\n';
}

Between 0 and 9 including the 9, yes.

-Albatross
and seems to be more faster
thank you so much for all
why random.h is better than rand() or srand()?


I guess you mean <random>.

The random number generation functions in the C++ random library have hard requirements on them to ensure they're actually good. I've got the standard open in front of me and it lays down a set of hard requirements in section 26, including some that I can but assume make some pretty solid enforcements.

The rand() function has no such restrictions, and historically has often been (and still is today) bloody awful (Albatross' OpenBSD above notwithstanding). For starters, you get a guarantee that the number generated will be between zero and 32767. What if you want random numbers up to 40000? You'll just have to hope that whoever wrote your rand() did a bit better. But you're just hoping.

Here are some implementations: https://stackoverflow.com/questions/4768180/rand-implementation
They're very flawed.

Watch the video I linked. It's STL being, as he always is, very informative.
Last edited on
thank you so much for all to all
Topic archived. No new replies allowed.