Skip to content

Instantly share code, notes, and snippets.

@warmans
Created January 13, 2012 18:10
Show Gist options
  • Save warmans/1607837 to your computer and use it in GitHub Desktop.
Save warmans/1607837 to your computer and use it in GitHub Desktop.
Modified Version of anagram-finder that reduces duplicate string operations
<?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