Last active
October 7, 2017 18:20
-
-
Save itumulak/da80af2e9cfc42e2e04369eeb30dcedc to your computer and use it in GitHub Desktop.
Anagram Puzzle. Oct. 7 DevCon Code Challenge.
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 | |
| $dictionary = [ | |
| 'epty', | |
| 'pety', | |
| 'yetpa', | |
| 'epyt' | |
| ]; | |
| $targetted_word = 'type'; | |
| function find_anagram( $dictionary, $targetted_word ) | |
| { | |
| $targetted_word_array = str_split( $targetted_word ); | |
| foreach ( $dictionary as $index => $dictionary_word ) | |
| { | |
| $dictionary_word_array = str_split( $dictionary_word ); | |
| // Make sure that both words matches letter count | |
| // Otherwise, if trailing letters matched in the loop it still mark it as an anagram. We need to avoid that... | |
| if ( count($dictionary_word_array) == count($targetted_word_array) ) | |
| { | |
| foreach ( $dictionary_word_array as $dictonary_word_letter ) | |
| { | |
| foreach ( $targetted_word_array as $_index => $targetted_word_letter ) | |
| { | |
| if ( $dictonary_word_letter == $targetted_word_letter ) // A matching letter was found! | |
| { | |
| $matches[$index][] = $dictonary_word_letter; // Store to a new array | |
| // Unset this key array to avoid infinite looping... | |
| // Carry on finding matching letters until the $dictionary_word_array is empty | |
| unset($dictionary_word_array[$_index]); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| return $matches; | |
| } | |
| $results = find_anagram($dictionary, $targetted_word); | |
| foreach ( $results as $anagram ) | |
| { | |
| if ( count( str_split($targetted_word) ) == count( $anagram ) ) | |
| { | |
| echo implode( '', $anagram ) . '<br />'; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment