August 24, 2018
Coin flip coding golf
A short coding golf snippet for a simple coin flip.
Full code
//generate a cryptographically secure pseudo-random string
$randomString = bin2hex(random_bytes(16));
//select the first char
$randomChar = substr($randomString,0,1);
//if this char is a number, use it
if(is_numeric($randomChar)){
$randomNumber = $randomChar;
}
//if not, use the numeric representation
else {
$randomNumber = strpos('abcdefghijklmnopqrstuvwxyz',$randomChar);
}
//check if the number is odd or even
$numericBoolean = $randomNumber % 2;
//odd = heads, even = tails
echo ($numericBoolean==1?'heads':'tails');
Shorted version
$a = substr(bin2hex(random_bytes(16)),0,1);
echo (((is_numeric($a)?$a:strpos('abcdefghijklmnopqrstuvwxyz',$a))%2)==1?'heads':'tails');
The code still feels far too long for such a simple task. The first thing I don’t like is the whole ABC string. So instead of checking if the first char is a number or not and then get the numeric value of a letter, I could just get the ASCII value of that character - regardless if it is a number or not.
I now can shorten the code to this:
echo ord(substr(bin2hex(random_bytes(16)),0,1))%2?'heads':'tails’;
But instead of using an alphanumeric value when I only need a number is still a bit of an overkill. So this time I am going to use the function random_int, which I already wrote about in a previous post[1].
echo random_int(PHP_INT_MIN,PHP_INT_MAX)%2?'heads':'tails’;
What if I just want a random boolean? I could get just that and pass 0 and 1 as the range.
echo random_int(0,1)?'heads':'tails';
This is IMHO the shortest most random possible coin flip solution.
Sources:
[1] https://blog.cipher.digital/article/php7-csprngTags: php, coding golf
« back
About the author
human, software engineer, tech enthusiast, security researcher
E-Mail: blog@cipher.digital
-----BEGIN PGP PUBLIC KEY BLOCK----- Version: OpenPGP (RSA-2048) xsBNBFjAYL4BCACsmBS6zE+0b7mZVtQhmfnRn3+IIQfT6WlE6izM39Q42yxj Hf2GOZU15Xc1x5RM9ZZx7HnMyTQWJMkwCzEba4Ju8dbn8gbFzLFp+mXAWQVJ NOhsLvt58X/k1nQ3HYaYAbJPFE4k89zlFUjBG+a1Qs0kNg5RkaSTcE4iV6L4 749LYRba1VFK1p3eIFmIh1zQnzwFY1WYJjvXHURZel8MA0BJTkmfOW4M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