Skip to content

Instantly share code, notes, and snippets.

@zeroasterisk
Last active May 28, 2016 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroasterisk/3e6a03798586d228992c to your computer and use it in GitHub Desktop.
Save zeroasterisk/3e6a03798586d228992c to your computer and use it in GitHub Desktop.
Big Dice Challenge
<?php
/**
* This is a simple test,
* to see how you'd approach solving what sounds like a simple problem
* but is in fact a bit tricky.
*
* Without using the functions rand(), array_rand(), shuffle(), or any variant
* can you make a big_dice() function which returns a random int between 1-100,
* with even distribution, and optimized runtime?
*
* You can and must use the dice() function within the big_dice() function
*
* Some simple testing code is included at the bottom,
* to ensure even distribution and to calculate runtime.
*
*
* @author __your_name_here__ <__your_email_here__>
* @date __today's_date__
*
*
*/
/**
* This is your only input function
* use this instead of rand(), etc
*
* @return int
*/
function dice() {
return rand(1, 6);
}
/**
* Here's the test -- create a random number between 1 and 100
* The distribution of these numbers should be even
* The runtime of this function should be decent
*
* @return int $result number between 1 and 100
*/
function big_dice() {
/*
figure out how to use the dice() function (as much as you like)
and just about anything else to generate a
random number between 1 and 100, with even distribution
but you can not use the rand() function or it's variants...
but you can not use the array_rand() or shuffle() functions or variants...
you can only use (and must use) the dice() function to generate it.
dice();
*/
return $result;
}
/**
* And here's the test of the big_dice() function
*
* echo's to page
*
* @return void
*/
function test_big_dice($test_limit = 100000) {
$big_dice_rolls = array();
$start = microtime(true);
for ($i=0; $i<$test_limit; $i++) {
$big_dice_rolls[] = big_dice();
}
$stop = microtime(true);
$duration = round((($stop - $start)), 4);
$breakdown = array_count_values($big_dice_rolls);
arsort($breakdown); // anomalies would be at the top or bottom
echo "Tested {$test_limit} rolls in ~{$duration} sec<br/>";
echo "Ended up with ".count($breakdown)." total outputs<br/>";
foreach ( $breakdown as $int => $occurances ) {
$pecentage = round($occurances / $test_limit * 100, 2);
echo "{$int} => [{$pecentage}%] {$occurances}<br/>";
}
}
# might as well test this thing!
test_big_dice();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment