Created
January 13, 2012 18:10
-
-
Save warmans/1607837 to your computer and use it in GitHub Desktop.
Modified Version of anagram-finder that reduces duplicate string operations
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 lineByLineImproved($anagramSeed) { | |
$fileinfo = new \SplFileInfo(RESOURCE.'wordlist.txt'); | |
$file = $fileinfo->openFile('r'); | |
$matchedWords = array(); | |
$anagramSeedLength = strlen($anagramSeed); //do this once | |
$anagramSeedAsArray = str_split($anagramSeed); //do this once | |
foreach($file as $line): | |
$line = trim($line); | |
if(strlen($line) == 0 || strlen($line) > $anagramSeedLength || $line == $anagramSeed){ | |
continue; | |
} | |
$word = str_split($line); | |
$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