Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include "FileHelper.h"
  2.  
  3. bool comp(pair<char, int> a, pair<char, int> b) {
  4.     return a.second > b.second;
  5. }
  6.  
  7. vector<string> FileHelper::open(const char* filename) {
  8.     streamsize size = -1;
  9.  
  10.     vector<string> text;
  11.     vector<pair<char, int>> chars;
  12.     size = this->proccessFile(filename, &text, &chars);
  13.  
  14.     int c = 1;
  15.     for (auto it : chars) {
  16.         map.insert(make_pair(it.first, c));
  17.         c++;
  18.     }
  19.  
  20.     return text;
  21. }
  22.  
  23. streamsize FileHelper::save(const char* filename, vector<char> &text) {
  24.     ofstream os(filename);
  25.  
  26.     for (auto ch : text) {
  27.         os << ch;
  28.     }
  29.     os.close();
  30.  
  31.     return 0;
  32. }
  33.  
  34. void FileHelper::loadReverseTable(const char* filename) {
  35.     vector<pair<char, int>> chars;
  36.     proccessFile(filename, nullptr, &chars);
  37.  
  38.     for (auto it : chars) {
  39.         reverse_map.push_back(it.first);
  40.     }
  41. }
  42.  
  43. streamsize FileHelper::proccessFile(const char* filename, vector<string>* text, vector<pair<char, int>>* chars) {
  44.     ifstream io(filename);
  45.  
  46.     io.seekg(0, io.end);
  47.     streamsize size = io.tellg();
  48.     io.seekg(0, io.beg);
  49.  
  50.     unordered_map<char, int> charmap;
  51.     string line;
  52.  
  53.     totalChars = 0;
  54.  
  55.     while (getline(io, line)) {
  56.         line.append("\n");
  57.         for (auto c : line) {
  58.             auto it = charmap.find(c);
  59.             if (it != charmap.end()) {
  60.                 charmap.at(c) += 1;
  61.             }
  62.             else {
  63.                 charmap.insert(make_pair(c, 1));
  64.             }
  65.  
  66.  
  67.             totalChars++;
  68.         }
  69.         if (text != nullptr) {
  70.             text->push_back(line);
  71.         }
  72.     }
  73.  
  74.     float entropy = 0.f;
  75.     for (auto it : charmap) {
  76.         float p = it.second / float(totalChars);
  77.  
  78.         if (p == 0.f) {
  79.             continue;
  80.         }
  81.  
  82.         entropy += (-p * log2(p));
  83.     }
  84.     printf("Entropy of %s: %f\n", filename, entropy);
  85.  
  86.     if (chars != nullptr) {
  87.         chars->assign(charmap.begin(), charmap.end());
  88.         sort(chars->begin(), chars->end(), comp);
  89.     }
  90.  
  91.     io.close();
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement