+ 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?🤔

17th Feb 2020, 2:01 AM
karangreat
karangreat - avatar
8 odpowiedzi
+ 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.
17th Feb 2020, 2:24 AM
Salman Nazeer
Salman Nazeer - avatar
+ 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".
17th Feb 2020, 3:06 AM
Arsenic
Arsenic - avatar
+ 5
It's a pseudo random sequence, not purely random.
17th Feb 2020, 10:18 PM
Sonic
Sonic - avatar
+ 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 😋)
17th Feb 2020, 4:36 AM
karangreat
karangreat - avatar
+ 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
17th Feb 2020, 4:55 AM
Arsenic
Arsenic - avatar
+ 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.
17th Feb 2020, 8:19 AM
Dennis
Dennis - avatar
17th Feb 2020, 9:08 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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
18th Feb 2020, 9:43 AM
Ishmam
Ishmam - avatar