-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathanagrams.php
More file actions
53 lines (49 loc) · 1.62 KB
/
anagrams.php
File metadata and controls
53 lines (49 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
// 5 kyu - Where my anagrams at?
// What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
//
// 'abba' & 'baab' == true
//
// 'abba' & 'bbaa' == true
//
// 'abba' & 'abbba' == false
// Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
//
// anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']); // => ['aabb', 'bbaa']
//
// anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']); // => ['carer', 'racer']
//
// anagrams('laser', ['lazing', 'lazy', 'lacer']); // => []
function anagrams(string $word, array $words): array {
$sorted = function($word) { $a = str_split($word); sort($a); return implode($a);};
$match = $sorted($word);
$result = [];
foreach($words as $w) {
$test = $sorted($w);
if ($test === $match) {
$result[] = $w ;
}
}
return $result;
}
// Alternative Solution:
//
// function anagrams(string $word, array $words): array {
// $sorted = function($word) { $a = str_split($word); sort($a); return implode($a);};
// $match = $sorted($word);
// return array_values(array_filter($words, function($w) use($match,$sorted){
// return $sorted($w) === $match;
// }));
// }
// function anagrams(string $word, array $words): array {
// $char = count_chars($word, 1);
// $res = [];
//
// foreach($words as $elem){
// if(count_chars($elem, 1) == $char){
// $res[] = $elem;
// }
// }
// return $res;
// }
?>