-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.cpp
More file actions
69 lines (62 loc) · 2.69 KB
/
Copy pathutils.cpp
File metadata and controls
69 lines (62 loc) · 2.69 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
#include "utils.h"
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <vector>
#include <climits>
namespace Utils {
Stats computeStats(const std::string& originalText,
const std::string& bits,
const std::unordered_map<unsigned char, std::string>& codes) {
Stats s;
s.originalBytes = originalText.size();
s.compressedBytes = (bits.size() + 7) / 8; // ceiling division
s.compressionRatio = s.originalBytes > 0
? (double)s.compressedBytes / s.originalBytes
: 0.0;
s.spaceSaving = (1.0 - s.compressionRatio) * 100.0;
s.uniqueChars = codes.size();
size_t minLen = SIZE_MAX, maxLen = 0;
for (auto& [ch, code] : codes) {
if (code.size() < minLen) { minLen = code.size(); s.shortestCode = code; }
if (code.size() > maxLen) { maxLen = code.size(); s.longestCode = code; }
}
return s;
}
void printStats(const Stats& s) {
std::cout << "\n--- Compression Stats ---\n";
std::cout << " Original size : " << s.originalBytes << " bytes\n";
std::cout << " Compressed size : " << s.compressedBytes << " bytes\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << " Compression ratio: " << s.compressionRatio << "\n";
std::cout << " Space saving : " << s.spaceSaving << "%\n";
std::cout << " Unique chars : " << s.uniqueChars << "\n";
std::cout << " Shortest code : " << s.shortestCode << " (" << s.shortestCode.size() << " bits)\n";
std::cout << " Longest code : " << s.longestCode << " (" << s.longestCode.size() << " bits)\n";
std::cout << "-------------------------\n\n";
}
void printCodes(const std::unordered_map<unsigned char, std::string>& codes) {
// Sort by code length for readability
std::vector<std::pair<unsigned char, std::string>> sorted(codes.begin(), codes.end());
std::sort(sorted.begin(), sorted.end(),
[](auto& a, auto& b){ return a.second.size() < b.second.size(); });
std::cout << "\n--- Huffman Codes ---\n";
std::cout << std::left << std::setw(10) << "Char"
<< std::setw(8) << "ASCII"
<< "Code\n";
std::cout << std::string(40, '-') << "\n";
for (auto& [ch, code] : sorted) {
std::string display;
if (ch == '\n') display = "\\n";
else if (ch == '\t') display = "\\t";
else if (ch == ' ') display = "SPACE";
else display = std::string(1, (char)ch);
std::cout << std::left << std::setw(10) << display
<< std::setw(8) << (int)ch
<< code << "\n";
}
std::cout << "---------------------\n\n";
}
} // namespace Utils