+ 6
How does the random function works?
In programming languages the random function show a random number everytime . But how it is making the decision that which number to display, is there any algo which is working behind the scenes?đ€
8 Answers
+ 5
Random functions, in C and C++ do not generate random numbers by themselves.
https://code.sololearn.com/ck4370pt2eOl/?ref=app
Run this twice and you will notice that the program generate same sequence each time.
Yes there are algorithms working behind the scenes. Sadly I dont know any.
+ 5
After looking in stdlib.h in my system I fount this đ defination of rand()
static long holdrand = 1L;
...
int rand()
{
return (((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
}
Actually just like Keri Vaadaa Makkale said rand() generates output which" looks random" from the definition of rand() we found that rand() doesn't take a seed, that means that everytime the program runs, calls to rand() will generate the exact same sequence of numbers as for what "looks random" means, well, it essentially means "if you eyeball the output, no obvious pattern jumps out at you".
+ 5
It's a pseudo random sequence, not purely random.
+ 4
This means there is an algo , so is it possible to hack games which works on random like spin wheel ?(this my sound like a dumb question but I am just curious đ)
+ 4
Not so easily. As some of them use a variety of seeds(seed is nothing but the sequence which the rand() follow) in their algo and they keep on switching between them.
But that doesn't means that it is impossible to crack them. By means of cryptography, one can easily find out the pattern in the sequences
+ 4
karangreat
Especially in older games, which often use a linear congruential generator, the same one rand() implements, you can relatively easily figure out the seed, and from there calculate all other seeds.
This is called rng manipulation and is often used in speedrunning.
For example yu-gi-oh forbidden memories has an rng manipulation category which uses it to calculate when the good cards drop in order to finish the game much more quickly.
+ 3
This is an example
https://code.sololearn.com/cCtBiottR5bj/?ref=app
+ 1
Actually no algorithm is working behind the scenes. There is a system file which generates random numbers from machine noise.
https://googleweblight.com/i?u=https://en.m.wikipedia.org/wiki//dev/random
Maybe this little piece of code can help you:
https://code.sololearn.com/cj9Q1q5HrftN/?ref=app