Last active
March 31, 2017 09:46
-
-
Save szepeshazi/7d9d4e6d7f6f74d7a6a584efabc72c38 to your computer and use it in GitHub Desktop.
Anagram test (PHP, multi-byte strings)
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 isAnagram($string1, $string2) { | |
if (!is_string($string1) || !is_string($string2)) { | |
return false; | |
} | |
$map1 = []; | |
$map2 = []; | |
for ($i = 0; $i < mb_strlen($string1); $i++) { | |
$char = mb_strtolower(mb_substr($string1, $i, 1)); | |
if (!ctype_space($char)) { | |
if (isset($map1[$char])) { | |
$map1[$char]++; | |
} else { | |
$map1[$char] = 1; | |
} | |
} | |
} | |
for ($i = 0; $i < mb_strlen($string2); $i++) { | |
$char = mb_strtolower(mb_substr($string2, $i, 1)); | |
if (!ctype_space($char)) { | |
if (isset($map2[$char])) { | |
$map2[$char]++; | |
} else { | |
$map2[$char] = 1; | |
} | |
} | |
} | |
return $map1 == $map2; | |
} | |
$anagramTests = [ | |
['a ', ' A', true], | |
['a', 'b', false], | |
['HA HA N N', 'hannah', true], | |
['', '', true], | |
[2, 2, false], | |
['ABCD', '一只快过速的棕色狐狸跳过懒狗', false], | |
['速的棕色', '色 棕 的 速', true] | |
]; | |
foreach ($anagramTests as $test) { | |
$testResult = isAnagram($test[0], $test[1]); | |
$assertFailMessage = "{$test[0]} and {$test[1]} are " . ($testResult ? 'anagrams,' : 'NOT anagrams,') . ' expected the opposite.'; | |
assert($testResult === $test[2], $assertFailMessage); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment