Created
January 13, 2012 18:45
-
-
Save warmans/1608008 to your computer and use it in GitHub Desktop.
Modified Version of anagram-finder that reduces duplicate string operations, this time using pre-loaded array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| public function preloadArray($anagramSeed) { | |
| $fileinfo = new \SplFileInfo(RESOURCE.'wordlist.txt'); | |
| $file = $fileinfo->openFile('r'); | |
| $anagramSeedLength = strlen($anagramSeed); | |
| $anagramSeedAsArray = str_split($anagramSeed); | |
| $wordArray = array(); | |
| foreach($file as $line): | |
| $line = trim($line); | |
| if(strlen($line) > 0 && strlen($line) <= $anagramSeedLength && $line != $anagramSeed){ | |
| $wordArray[] = $line; | |
| } | |
| endforeach; | |
| $matchedWords = array(); | |
| foreach($wordArray as $key=>$wordString): | |
| $word = str_split($wordString); | |
| $matchedLetters = 0; | |
| $letterPool = $anagramSeedAsArray; | |
| foreach($word as $key=>$letter): | |
| $foundLetterKey = array_search($letter, $letterPool); | |
| if($foundLetterKey !== FALSE){ | |
| unset($letterPool[$foundLetterKey]); | |
| $matchedLetters++; | |
| } | |
| endforeach; | |
| if($matchedLetters == count($word)){ | |
| $matchedWords[] = implode("", $word); | |
| } | |
| endforeach; | |
| return $matchedWords; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment