/
najczestrza_litera.php
102 lines (87 loc) · 2.89 KB
/
najczestrza_litera.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/*
* Napisz funkcję która pobiera napis, a zwróci tablice w której pierwszyme lementem będzie najczęściej występujący znak, a drugim ile razy ten znak wystapił z tym napisie.
* W przypadku w ktorym kilka znaków ma taką samą ilość powtórzeń powinien być zwrócony ten który wystepuje najwcześniej w podanym napisie
*
* Przykłady:
* mostOftenCharacter("Ala ma kota") => ['a', 3] // Duża litera A to inny znak
* mostOftenCharacter("kkkeefflll") => ['k', 3] // k i l majątyle samo powtórzeń ale k jest wcześniej
*/
function stringToArray($myString)
{
$myArray = array();
$j = 0;
for ($i = 0; $i < strlen($myString); $i++) {
$myArray[$i] = $myString[$j];
$j++;
}
return $myArray;
}
function mostOftenCharacter($string)
{
$myArray = stringToArray($string);
$resultArray = array();
$k = 0;
$counts = array_count_values($myArray);
foreach ($myArray as $value) {
$maxRepeat = $counts[$myArray[$k]];
$resultArray[0] = $counts[$myArray[0]];
if ($resultArray[0] < $counts[$myArray[$k]]) {
$resultArray[0] = $myArray[$k];
$resultArray[1] = $counts[$myArray[$k]];
}
else {
$resultArray[0] = $myArray[0];
$resultArray[1] = $counts[$myArray[0]];
}
$k++;
}
return $resultArray;
}
/*
* Kod popniżej służy wygenerowaniu testów i strony poglądaowej - nie modyfikujcie go!
*/
$testCases = [["Ala ma kota", ['a', 3]], ["kkkeefflll", ['k', 3]], ["elkkeldsllael", ["l", 5]], ["ertTTtrr", ["r", 3]]];
$results = "";
foreach($testCases as $case){
if(($funcValue = mostOftenCharacter($case[0])) === $case[1]){
$results .= "<tr class='success'><td> Ok </td><td>{$case[0]}</td><td>[".implode($case[1], ",")."]</td><td>[".implode($funcValue, ",")."]</td></tr>";
}
else{
$results .= "<tr class='danger'><td> Fail </td><td>{$case[0]}</td><td>[".implode($case[1], ",")."]</td><td>[".implode($funcValue, ",")."]</td></tr>";
}
}
echo("
<!DOCTYPE html>
<html lang='pl'>
<head>
<meta charset='utf-8'>
<title>Najczęściej występujący znak</title>
<link href='./css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container'>
<div class='jumbotron'>
<h1>Najczęściej występujący znak</h1>
<p><a class='btn btn-lg btn-success' href='javascript:window.location.reload();' role='button'>Odświerz</a></p>
</div>
<div class='row'>
<h1>Testy:</h1>
<table class='table'>
<thead>
<tr>
<th>Stan testu:</th>
<th>Dane:</th>
<th>Wartość spodziewana:</th>
<th>Wartość otrzymana:</th>
</tr>
</thead>
<tbody>
$results
</tbody>
</table>
</div>
</div>
</body>
</html>
");