Skip to content

Instantly share code, notes, and snippets.

@warmans
Created January 13, 2012 18:45
Show Gist options
  • Select an option

  • Save warmans/1608008 to your computer and use it in GitHub Desktop.

Select an option

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.
<?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