-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2.php
More file actions
77 lines (63 loc) · 2.11 KB
/
q2.php
File metadata and controls
77 lines (63 loc) · 2.11 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
## Question 2 - Search pattern
Please write a *function* that returns the index of the best match, when looking at an array of values.
```php
$needle = "London, England, uk";
$haystack = array(
1 => array("London", "Ontario", "Canada"),
8 => array("Greater London", "England", "UK"),
4 => array("London", "England", "United Kingdom"),
9 => array("London", "California", "United States")
);
echo best_match($needle, $haystack);
function best_match($needle, $haystack)
{
// Your code here
}
```
What I am looking for is code that can analyse and compare each element of each array and rank them according to the the number of characters that are matched in each.
Expected output:
```
8
```
Tip: be careful about case sensitivity and spaces.
*/
function lowercase_array(array $array): array {
return array_map(function ($value) {
if (is_array($value)) {
return lowercase_array($value);
} else {
return strtolower($value);
}
}, $array);
}
function best_match(string $needle, array $haystack) : int
{
// Lowercase both the needle and haystack elements for case-insensitive matching
$needle = strtolower($needle);
$haystack_lower = lowercase_array($haystack);
$best_match_score = -1;
$best_match_key = -1;
// Calculate the number of matching characters between the needle and each sublist element
foreach($haystack_lower as $key => $sublist) {
$match_score = 0;
foreach ($sublist as $item) {
// Use substr_count for multiple occurrences
$match_score += substr_count($needle, $item);
}
if ($match_score > $best_match_score) {
$best_match_score = $match_score;
$best_match_key = $key;
}
}
return $best_match_key;
}
$needle = "London, England, uk";
$haystack = array(
1 => array("London", "Ontario", "Canada"),
8 => array("Greater London", "England", "UK"),
4 => array("London", "England", "United Kingdom"),
9 => array("London", "California", "United States")
);
echo best_match($needle, $haystack);