Classroom Programming
page was last updated: Mar 09, 2017 23:36
forum
sorry ): this page is incomplete. feel free to ask me directly for any help ^_^
Random X11

Intro

Sometimes, just sometimes? We want random numbers, randomly genereated level's guessing games, variety, trolling, etc. Just a quick thing about random though because you may run into some interesting behavior. Espcially for computers, there is NO such thing as random. This is the behavior of deterministic machines. The machine only knows where it is because of where it was before. This means that the computer can't acutally make anything from scratch, it is all based off of something else. And so, you'll hear alot of hte terms "pseudo-random" and "true random."

So how does a computer get random then? We take something we have, lets say the current position of a fruit fly buzzing around, and perform some algorithms to turn it into a number we can use.

Random in C++

Old school way (pre c++11)

The rand() and srand(u seed) are defined in the cstdlib so include that. When you call the function rand() it will return an integer between 0 and RAND_MAX. (inclusive?) RAND_MAX being some constant number defined elsewhere.

"WHUT?!? how to number between 0-10?" simple rand() % 11. 11 is because of the way modulus works. Remember, modulus is the REMAINDER of a division. to get range of 4-8. rand() % 5 + 4. or generally rand() % [range+1] + [offset from zero].

Fresh Seeds

What you'll notice pretty quickly when testing is that it is always giving the SAME "random" numbers!! That is what srand(uint) is for. You need to seed the random engine with a starting point (part of that... deterministic machine again). sounds like a great one would be something that always changes like... TIME! :D

Time stuff is defined in the ctime library. time(NULL) will give you the current time as a number. SO! That means lets load it like this, srand(time(NULL)) and everytime the code runs, we reseed the random engine with a new time. Finally!, actually different randoms.

New way (c++11)

stuffs

The Difference

the speed, memory, randomness difference between new and old ways

old way

#include <cstdlib> import library for random
#include <time.h> import library for time
srand(time(NULL)) seed the random engine with time because it always changes
rand() returns a positive random number integer

new way (c++11)

References

rand() <cstdlib>
<random>(c++11)