- array_search: documentation ( source)
- shuffle: documentation ( source)
- in_array: documentation ( source)
- range: documentation ( source)
- rand: documentation ( source)
<?php
// Start / End range
$start = 1;
$end = 100;
// The two statements below allowed me to suggest which number to remove
// I opted to use a file because I thought it was less obvious than passing
// another argument.
//$remove = is_readable(__DIR__ . '/remove') ? trim(file_get_contents(__DIR__ . '/remove')) : false;
//$remove = isset($argv[2]) ? true : false;
// Otherwise we simulate which number we have removed
$remove = rand($start, $end);
$random = isset($argv[1]) ? true : false;
// Create the range
$list = range($start, $end);
// Determine whether the array should be random
$random and shuffle($list);
// Because $remove is optional (if user defined) we wrap this with an if
if($remove) {
$key = array_search($remove, $list);
// Make sure the key exists otherwise php treat false == 0
// meaning the first element of the array would be removed if the key wasn't found
if($key !== false) {
unset($list[$key]);
}
}
// Time to search for the number that was removed
// I can't remeber whether I'm allowed to use the in_array method, but this loops through the range 1..100
// and determines whether that value exists.
$found = false;
for($i = $start; $i <= $end; $i++) {
if(!in_array($i, $list)) {
$found = $i;
print $i . " was removed\n"; break;
}
}
if($found == $remove) {
print "Successfuly found the missing number\n";
}