Skip to content

Instantly share code, notes, and snippets.

@lesterchan
Created July 5, 2013 09:57
Show Gist options
  • Save lesterchan/5933465 to your computer and use it in GitHub Desktop.
Save lesterchan/5933465 to your computer and use it in GitHub Desktop.
You have a array of a million integers. They are ordered 1,2,3,4,5... all the way to 1,000,000. I shuffle the array and I remove two of the numbers. Write a function (in any language of your choice) that takes the array of 999,998 numbers and efficiently determines which two numbers between 1 and 1,000,000 have been removed.
<?php
// Max Integer
define('MAX', 1000000);
// Create An Array Till MAX
$original = range(1, MAX);
// Shuffle The Array While Preserving Keys
$shuffle = $original;
shuffle_assoc($shuffle);
// Pick Any 2 Keys From The Array
$rand_keys = array_rand($shuffle, 2);
// Print Which Keys Are Removed
echo 'Removed: '.$shuffle[$rand_keys[0]].', '.$shuffle[$rand_keys[1]]."\n";
// Remove It From Array
unset($shuffle[$rand_keys[0]]);
unset($shuffle[$rand_keys[1]]);
// Find Out Which Keys Are Removed
$time_start = microtime(true);
$removed = array_values(array_diff($original, $shuffle));
echo 'Removed: '.$removed[0].', '.$removed[1]."\n";
$time_end = microtime(true);
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key)
{
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
echo 'Time Taken: '.(($time_end-$time_start)/1000).' ms'."\n";
?>
@lesterchan
Copy link
Author

09:54:09 lchan@cjlab-dw1:/var/www/lc/web(master)$ php test.php
Removed: 49127, 971013
Removed: 49127, 971013
Time Taken: 0.074328508138657 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment