-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfreq_seq.php
More file actions
37 lines (32 loc) · 1.13 KB
/
freq_seq.php
File metadata and controls
37 lines (32 loc) · 1.13 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
<?php
// Return an output string that translates an input string s/$s by replacing each character in s/$s with a number representing the number of times that character occurs in s/$s and separating each number with the character(s) sep/$sep.
//
// freq_seq("hello world", "-"); // => "1-1-3-3-2-1-1-2-1-3-1"
// freq_seq("19999999", ":"); // => "1:7:7:7:7:7:7:7"
// freq_seq("^^^**$", "x"); // => "3x3x3x2x2x1"
function freq_seq(string $s, string $sep): string {
$result = array_map(function($x) use ($s) {
return substr_count($s, $x);
}, str_split($s));
return join($sep, $result);
}
// Alternative solution:
// function freq_seq(string $s, string $sep): string {
// $results = [];
//
// $chars = str_split($s);
// $countValues = array_count_values($chars);
// foreach ($chars as $char) {
// $results[] = $countValues[$char];
// }
//
// return implode($sep, $results);
// }
// function freq_seq(string $s, string $sep): string {
// $s = str_split($s);
// $dict = array_count_values($s);
// return join($sep, array_map(function ($char) use ($dict) {
// return $dict[$char];
// }, $s));
// }
?>