Created
January 30, 2017 22:13
-
-
Save dmitrybubyakin/fde5b570561e349f886214e4a069144c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <string> | |
using namespace std; | |
int main(){ | |
map<char, long double> abc; | |
map<char, long double> lows; | |
string msg; | |
cout<<"msg>"; | |
getline(cin,msg); | |
int len = msg.length(); | |
for(auto i = 0; i < len; i++){ | |
abc[msg[i]] += 1.0 / len; | |
} | |
long double code = 0.0, high = 1.0, low = 0.0, r = 0.0; | |
long double l, h = 0.0, highRange, lowRange, range; | |
char c; | |
string decoded; | |
for(auto i: abc){ | |
l = h; | |
h += i.second; | |
lows[i.first] = l; | |
//printf("%c %4.2LF %4.2LF - %4.2LF\n",i.first, i.second, l, h); | |
} | |
for(auto c: msg){ | |
lowRange = lows[c]; | |
highRange = lowRange + abc[c]; | |
range = high - low; | |
high = low + range * highRange; | |
low = low + range * lowRange; | |
printf("%c %12.14LF %12.14LF\n", c, low, high); | |
} | |
code = low; | |
cout<<endl; | |
while(--len >= 0){ | |
for(auto i: lows){ | |
if(i.second <= code && code < i.second + abc[i.first]){ | |
c = i.first; | |
lowRange = i.second; | |
range = abc[c]; | |
decoded += c; | |
break; | |
} | |
} | |
printf("%c %12.14LF\n",c,code); | |
code = (code - lowRange) / range; | |
} | |
cout<<decoded<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment