Skip to content

Instantly share code, notes, and snippets.

@aldiunanto
Created September 22, 2019 09:36
Show Gist options
  • Save aldiunanto/4413986d92b51c1f0078588996c31454 to your computer and use it in GitHub Desktop.
Save aldiunanto/4413986d92b51c1f0078588996c31454 to your computer and use it in GitHub Desktop.
Find anagram from given array
<?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