If you are new to ClojureScript I highly recommend copying and pasting the code snippets below into app.klise.tech, my personal favorite online REPL for evaluating ClojureScript code.
My second way of creating random numbers in clojurescript is to use the built-in clojure function, rand.
Imo just "(math/random)" it much shorter, cleaner, and just makes me feel good when I read and write it.
Don't you just love function names that are so obvious you almost don't even need to look at the documentation to make sure what it does? Well, rand-int just returns a random int, and to quote the doc string exactly it, "Returns a random integer between 0 (inclusive) and 1 (exclusive)." This one basically just takes the random float that we would make between 0 and n as passes it into "Math/floor". You can see the true implementation in all its breathtaking awe and beauty here.
I'll be honest, I found out about rand-nth from the first time I ctrl+ clicked rand and started snooping around clojurescript's core.cljs file, but I'm glad I did because it's one cool ass motherf%ckin' function! Basically, it's a rand function for collections that will return a random element from the collection.
A random number is like a blooming cherry blossom that must be nurtured and appreciated. If you have three objects in front of you, how do you truly randomly choose one? There's something about as humans that we cannot by our own brains generate totally random numbers. If you needed a random number on the spot what would you do? You might pull out your cell phone and Google for "random number generator", and that's exactly my point. The ability to create this unbiased variety of selection is an incredible power wielded by few other than the computer programmer. Take it, my friends, and do great things with it!
The posts on this site are written and maintained by Jim Lynch. About Jim...