-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncode.php
63 lines (55 loc) · 1.24 KB
/
Encode.php
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
<?php include 'parts/headart.php'; ?>
<h1>encode</h1>
<h2>Exercice</h2>
cette fonction retour une chaine avec avec le nombre d'occurences consécutives de chaque lettre
<br>
ex : aaabbbz => 3a3b1z
<h2>Code</h2>
<pre>
function encode(string $paintText): string
{
$chars = str_split($paintText);
$char = $chars[0];
$cpt = 0;
$reponse = "";
foreach ($chars as $item) {
if ($char == $item) {
$cpt++;
} else {
$reponse .= $cpt . $char;
$cpt = 1;
$char = $item;
}
}
$reponse .= $cpt . $char;
return $reponse;
}
$chaine = "aaabbz";
echo '<br>Chaine : ' . $chaine;
echo '<br>Encode : ' . encode($chaine);
</pre>
<h2>Solution</h2>
<?php
function encode(string $paintText): string
{
$chars = str_split($paintText);
$char = $chars[0];
$cpt = 0;
$reponse = "";
foreach ($chars as $item) {
if ($char == $item) {
$cpt++;
} else {
$reponse .= $cpt . $char;
$cpt = 1;
$char = $item;
}
}
$reponse .= $cpt . $char;
return $reponse;
}
$chaine = "aaabbz";
echo '<br>Chaine : ' . $chaine;
echo '<br>Encode : ' . encode($chaine);
?>
<?php include 'parts/footerPart.php'; ?>