-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShanon.php
More file actions
112 lines (99 loc) · 3.03 KB
/
Copy pathShanon.php
File metadata and controls
112 lines (99 loc) · 3.03 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
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
103
104
105
106
107
108
109
110
111
112
<?php
declare(strict_types=1);
use League\CLImate\CLImate;
/* -------------------------------------------------------
_..
.qd$$$$bp.
.q$$$$$$$$$$m.
.$$$$$$$$$$$$$$
.q$$$$$$$$$$$$$$$$
.$$$$$$$$$$$$P\$$$$;
.q$$$$$$$$$P^"_.`;$$$$
q$$$$$$$P;\ , /$$$$P
.$$$P^::Y$/` _ .:.$$$/
.P.:.. \ `._.-:.. \$P
$':. __.. : :.. :'
/:_..::. `. .:. .'|
_::.. T:.. / :
.::.. J:.. : :
.::.. 7:.. F:.. : ;
_.::.. |:.. J:.. `./
_..:::.. /J:.. F:. :
.::::.. .T \:.. J:. /
/:::... .' `. \:.. F_o'
.:::... .' \ \:.. J ;
::::... .-'`. _.`._\:.. \'
':::... .' `._7.-'_.- `\:. \
\:::... _..-'__.._/_.--' ,:. b:. \._
`::::..-"_.'-"_..--" :.. /):. `.\
`-:/"-7.--"" _::.-'P::.. \}
_....------"""""" _..--".-' \::.. `.
(::.. _...----""" _.-' `---:.. `-.
\::.. _.-"""" `""""---"" `::...___)
`\:._.-""" GingTeam
------------------------------------------------------- */
require __DIR__.'/vendor/autoload.php';
$cli = new CLImate();
$input = $cli->input('Nhập chuỗi cần mã hóa:');
$text = $input->prompt();
$len = strlen($text);
if (0 === $len) {
$cli->error('Chuỗi rỗng');
exit(1);
}
$data = [];
$ctx = (array) count_chars($text, 1);
arsort($ctx);
$n = count($ctx);
foreach ($ctx as $ascii => $v) {
$data[] = [chr($ascii), $v];
}
$h = 0;
$ntb = 0;
$table = [];
$f = 0;
$expr = fn (int $x): string => sprintf('%d / %d', $x, $len);
foreach ($data as $i => $d) {
/** @var int[] $d */
$p = $d[1] / $len;
$n = (int) log(1 / $p, 2) + 1;
$pu = $expr($d[1]);
$fu = $expr($f);
$h += $p * log(1 / $p, 2);
$ntb += $n * $p;
$table[] = [
'Ký tự' => $d[0],
'P(u)' => $pu,
'F(u)' => $fu,
'N' => $n,
'Mã hóa' => encode(calc($fu), $n),
];
$f += $d[1];
}
$cli->table($table);
$cli->info('H = '.round($h, 2));
$cli->info('Ntb = '.round($ntb, 2));
/**
* @internal
*/
function encode(float $f, int $n): string
{
$result = '';
for ($i = 0; $i < $n; ++$i) {
$f *= 2;
if ($f >= 1) {
$result .= '1';
--$f;
} else {
$result .= '0';
}
}
return $result;
}
/**
* @internal
*/
function calc(string $expr): float
{
return (float) eval('return '.$expr.';');
}