-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshanonFano.cpp
More file actions
59 lines (46 loc) · 1.75 KB
/
shanonFano.cpp
File metadata and controls
59 lines (46 loc) · 1.75 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
#include <vector>
#include <algorithm>
using namespace std;
struct Symbol {
char ch;
double probability;
string code;
};
// Функция для разделения массива символов на две группы с приблизительно равной суммой вероятностей
int findSplitIndex(vector<Symbol>& symbols, int start, int end) {
double totalSum = 0.0;
for (int i = start; i <= end; ++i) totalSum += symbols[i].probability;
double sum = 0.0;
for (int i = start; i <= end; ++i) {
sum += symbols[i].probability;
if (sum >= totalSum / 2) return i;
}
return start;
}
// Рекурсивное кодирование методом Шеннона-Фано
void shannonFano(vector<Symbol>& symbols, int start, int end) {
if (start >= end) return;
int split = findSplitIndex(symbols, start, end);
for (int i = start; i <= split; ++i) symbols[i].code += "0";
for (int i = split + 1; i <= end; ++i) symbols[i].code += "1";
shannonFano(symbols, start, split);
shannonFano(symbols, split + 1, end);
}
int main() {
vector<Symbol> symbols = {
{'A', 0.190}, {'B', 0.165}, {'C', 0.137}, {'D', 0.122},
{'E', 0.112}, {'F', 0.107}, {'G', 0.091}, {'H', 0.076}
};
// Сортировка по убыванию вероятности
sort(symbols.begin(), symbols.end(), [](const Symbol& a, const Symbol& b) {
return a.probability > b.probability;
});
// Запуск алгоритма
shannonFano(symbols, 0, symbols.size() - 1);
// Вывод кодов
cout << "Коды Шеннона-Фано:" << endl;
for (const auto& sym : symbols) {
cout << sym.ch << ": " << sym.code << endl;
}
return 0;
}