Skip to content

Instantly share code, notes, and snippets.

@evert
Created November 21, 2012 12:30
Show Gist options
  • Save evert/4124639 to your computer and use it in GitHub Desktop.
Save evert/4124639 to your computer and use it in GitHub Desktop.
Words With Enemies
<?php
if ($argc < 2) {
echo "Usage: \n";
echo "\n";
echo "1. Wait till you get an invite for a silly wordgame\n";
echo "2. execute $argv[0] [letters]\n";
echo "3. Win\n";
die();
}
$dictionaryLocations = array(
'/usr/share/dict/words',
);
$ok = false;
foreach($dictionaryLocations as $dict) {
if (file_exists($dict)) {
$ok = true;
break;
}
}
if (!$ok)
die('Could not find dictionary');
echo "Using dictionary: $dict\n";
$letters = array();
foreach(str_split($argv[1]) as $letter) {
if (isset($letters[$letter])) {
$letters[$letter]++;
} else {
$letters[$letter] = 1;
}
}
$words = file($dict);
$foundWords = array();
echo "Searching..\n";
foreach($words as $word) {
$word = trim($word, "\r\n");
$l = $letters;
foreach(str_split($word) as $wl) {
if (!isset($l[$wl]) || $l[$wl]==0) {
continue 2;
}
$l[$wl]--;
}
$foundWords[] = $word;
}
usort($foundWords, function($a, $b) {
if (strlen($a)===strlen($b)) return 0;
return strlen($a) > strlen($b)?1:-1;
});
foreach($foundWords as $foundWord) {
echo str_pad(strlen($foundWord),3), $foundWord, "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment