Skip to content

Instantly share code, notes, and snippets.

@simplesessions
Created July 22, 2010 00:17
Show Gist options
  • Save simplesessions/485369 to your computer and use it in GitHub Desktop.
Save simplesessions/485369 to your computer and use it in GitHub Desktop.
/**
* Solution to the following:
* Given a dictionary, output all word pairs where both words share all their letters except the last two, which are distinct and reversed.
*
* Notes:
* - Use a reasonable dictionary of your choice
* - Potential word pairs are: "ear, era" ; "revies, revise" ; "burglaries, burglarise"
* - "shear, era" is not a valid pair because "she" != "e"
* - "bell, bell" is not a valid pair because the last two letters are not distinct
* - This will be benchmarked
* - Work on this problem in C, C++, Java, Perl, PHP, Python or a similar language.
* - Don't e-mail to ask for clarifications on this question.
* Make reasonable assumptions and justify them in a README if you feel the need
*/
<?php
$time = microtime();
$results = array();
$dictionary = array();
// copy the contents of the file to our dictionary
$file = fopen("dictionary.txt", "r");
if ($file) {
while (!feof($file)) {
$dictionary[] = trim(fgets($file));
}
fclose($file);
}
$dictionary = array_unique($dictionary);
// compile our word pairs from the dictionary
while ($curr = array_shift($dictionary)) {
$length = strlen($curr);
if ($length < 2 || $curr[$length-1] == $curr[$length-2])
continue;
$search = substr($curr, 0, $length-2) . $curr[$length-1] . $curr[$length-2];
$result = array_search($search, $dictionary);
if ($result !== FALSE) {
$results[] = $curr . ", " . $dictionary[$result];
unset($dictionary[$result]);
}
}
$time = microtime() - $time;
echo "<p>" . implode($results, '<br>') . "</p>";
echo "<p>Found " . count($results) . " pairs in " . ($time) . " seconds</p>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment