PHP ANAGRAM TOOL v2.0

the description

I said in my first anagram tool attempt that I wanted to create a recursive function to create the anagrams. That's what this is.

Because of reasons explained below this script is processor-intensive, so I've limited the character length of anagramizable words to 10. I also added a timer so that you can see how long it takes the processor to find the anagrams.

the bad

Ultimately, it is a solution, but not a very good one. It will create anagrams, and it will spit out correctly spelled ones. The problem is that it's creating the anagrams using brute-force. It pieces together every anagram one character at a time, using every possible character combination available. This works nicely for 4 letter words which only have 64 possible combinations (including 1, 2, and 3 character word), but quickly gets out of control as you enter larger words. 7 character words have 13,699 anagrams that need to be built, and that number jumps to nearly a million at 986,409 for 9 character words. That's a ton of processing the webserver has to handle.

Another problem with the solution is that it will test duplicate anagrams. For example, if you typed 'aaaaa' into the tool, it will put together 325 anagrams to test, not recognizing that it really only needs to do 4: a, aa, aaa, and aaaa. Solutions for this could actually create more work for the server than it's saving it from doing, though. Even if I was able to come up with a lightweight solution to this problem, I doubt that it would make much of an impact on the overall workload. When one million anagrams are being built, I would estimate that hardly 1% of those would be duplicates.

the good

  • it's recursive!
  • it filters out duplicate anagrams
  • it could theoretically handle words of any length (the first attempt could only show anagrams 4 characters long or less)
  • it shows anagrams of any character length less-than or equal-to the length of the original word
  • under 30 lines of code

the implementation

the code

<?php

$anagrams = array();
function anagramize($leftovers,$pspell_link,$anagram='',$counter=array('count'=>0,'word_count'=>0)) {
	global $anagrams;
	for($i=0; $i<strlen($leftovers); $i++) {
		$counter['count'] += 1;

		$new_anagram = $anagram;
		$new_anagram .= $leftovers[$i];
		if(pspell_check($pspell_link, $new_anagram)) {
			if(!in_array($new_anagram, $anagrams)) {
				if($counter['count']>1) echo ', ';
				echo $new_anagram;
				$anagrams[] = $new_anagram;
				$counter['word_count'] += 1;
			}
		}

		$letterToRemove = $leftovers[$i];
		$newLeftovers = substr_replace($leftovers,'',$i,1);

		if(strlen($newLeftovers) > 0) {
			$counter = anagramize($newLeftovers,$pspell_link,$new_anagram,$counter);
		}
	}
	return $counter;
}
?>