Betting on the Lottery with Bash and /dev/urandom
This year’s Mega-Sena New Year’s Eve lottery here in Brazil has an accumulated prize of R$850 million, that’s approximately 160 million US dollars. I’m definitely throwing in a ticket.
This lottery draws six numbers from 1 to 60. You win when your bet matches 4, 5, or 6 numbers. You can bet on 6 numbers or more, up to 20, in the same game. The more numbers you bet, the more expensive the game is. The odds of winning this lottery when betting six numbers is 1 in 50,063,860, pretty low. The house always wins.
I’m betting this year, and I want an easy way to choose my numbers. I’m
embracing the chaos and going random. If I had a 60-sided dice, I’d roll it six
times. Instead, I’ll use /dev/urandom as a source of luck, because why not
let a cryptographically secure random number generator decide my fate?
There are a few ways of picking random numbers from /dev/urandom, I wrote an
article about that in the past. But
this time I need numbers in a very small range, and I want to try a different
approach.
I’m going to use shuf to generate six unique random numbers, from 1 to
60, using /dev/urandom as source of randomness. It is pleasantly
straightforward:
$ shuf -i 1-60 --random-source=/dev/urandom -n 6
52
9
43
47
45
21
And that’s it: my randomly blessed lottery ticket for the year.
Maybe I win the lottery? Probably not. Did I have fun with a Linux-powered ritual? Absolutely!