Guest User

Untitled

a guest
Dec 16th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include<iostream>
  2. #include<unordered_map>
  3. #include<vector>
  4. using namespace std;
  5.  
  6. struct node{
  7. double prob, range_from, range_to;
  8. };
  9.  
  10. double encoding(unordered_map<char, node> arr, string s){
  11. cout<<"\nEncoding\n";
  12. double low_v=0.0, high_v=1.0, diff= 1.0;
  13. cout<<"Symbol\tLow_v\tHigh_v\tdiff\n";
  14. for(int i=0; i<s.size(); i++){
  15. high_v= low_v+ diff* arr[s[i]].range_to;
  16. low_v= low_v+ diff* arr[s[i]].range_from;
  17. diff= high_v- low_v;
  18. cout<<s[i]<<"\t"<<low_v<<"\t"<<high_v<<"\t"<<diff<<endl;
  19. }
  20. return low_v;
  21. }
  22.  
  23. string decoding(unordered_map<char, node> arr, double code_word, int len){
  24. cout<<"\nDecoding: \n";
  25. char ch;
  26. string text= "";
  27. int j=0;
  28. unordered_map<char, node>:: iterator it;
  29. cout<<"Code\tOutput\tRange_from\tRange_to\n";
  30. while(j<len){
  31. cout<<code_word<<"\t";
  32. for(it= arr.begin(); it!=arr.end(); it++){
  33. char i= (*it).first;
  34. if(arr[i].range_from<= code_word && code_word< arr[i].range_to){
  35. ch= i;
  36. code_word= (code_word-arr[i].range_from)/(arr[i].range_to- arr[i].range_from);
  37. break;
  38. }
  39. }
  40. cout<<ch<<"\t"<<arr[ch].range_from<<"\t\t"<<arr[ch].range_to<<endl;
  41. text+= ch;
  42. j++;
  43. }
  44. return text;
  45. }
  46.  
  47. int main(){
  48. int n;
  49. cout<<"Enter number of characters: ";
  50. cin>>n;
  51. unordered_map<char, node> arr;
  52. vector<char> ar;
  53. double range_from= 0;
  54. cout<<"Enter probability of each character:\n";
  55. for(int i=0; i<n; i++){
  56. char ch;
  57. cin>>ch;
  58. ar.push_back(ch);
  59. cin>>arr[ch].prob;
  60. arr[ch].range_from= range_from;
  61. arr[ch].range_to= range_from+ arr[ch].prob;
  62. range_from= arr[ch].range_to;
  63. }
  64. cout<<"Symbol\tProbability\tRange_from\tRange_to\n";
  65. cout<<"----------------------------------------------------\n";
  66. for(int i=0; i<ar.size(); i++){
  67. char ch= ar[i];
  68. cout<<ch<<"\t"<<arr[ch].prob<<"\t\t"<<arr[ch].range_from<<"\t\t"<<arr[ch].range_to<<endl;
  69. }
  70. cout<<endl;
  71. string s;
  72. cout<<"Enter text: ";
  73. cin>>s;
  74. double code_word= encoding(arr, s);
  75. cout<<"Code word for "<<s<<" is: "<<code_word<<endl;
  76. string text= decoding(arr, code_word, s.size());
  77. cout<<"Text for "<<code_word<<" is: "<<text<<endl;
  78.  
  79. }
Add Comment
Please, Sign In to add comment