Created
September 22, 2019 09:36
-
-
Save aldiunanto/4413986d92b51c1f0078588996c31454 to your computer and use it in GitHub Desktop.
Find anagram from given array
This file contains 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 | |
function findAnagrams($dict) | |
{ | |
$anagrams = []; | |
$_sortString = function ($str) { | |
$l = str_split($str); | |
sort($l); | |
return implode('', $l); | |
}; | |
foreach ($dict as $word) | |
{ | |
$index = $_sortString($word); | |
$anagrams[$index][] = $word; | |
} | |
return array_filter($anagrams, function ($el) { | |
return count($el) > 1; | |
}); | |
} | |
$dict = ["bat", "code", "cat", "act", "cab", "crazy", "tac"]; | |
print_r(findAnagrams($dict)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment