Advertisement
Okorosso

Hartly by for loop cycles and pseudo map

Mar 19th, 2021
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct myMapNode { // create our own structure map like type
  5.     char letter;
  6.     int count;
  7.     std::string bitRepr; // binary representation of number in array
  8. };
  9.  
  10. void addLetter(std::vector<myMapNode> &vec, char letterToAdd) { // create map like array and append elem if arr has no
  11.                                                             // or update count to +1 if element is exists
  12.     int len = vec.size();
  13.     for (int i = 0; i < len; i++) {
  14.         if (letterToAdd == vec[i].letter) {
  15.             vec[i].count++;
  16.             return;
  17.         }
  18.     }
  19.     vec.push_back(myMapNode{letterToAdd, 1});
  20. }
  21.  
  22. std::string convertToBin(int numCount, int n) { // bitRepr to bitRepr convert int 0 or 1 to char and add to our result string
  23.     std::string output;
  24.     for (int i = 0; i < numCount; i++) {
  25.         output += ((char) n % 2) + 48; // %2 is 0 or 1 and is last num in bitRepr representation
  26.         // +48 because 48 is position 0 in ascii
  27.         n >>= 1; // bitRepr shift to new int
  28.     }
  29.     return output;
  30. }
  31.  
  32. int bitsCount(int n) { // function for find max count of bits in out last index in array
  33.     int count = 0;
  34.     while (n) {
  35.         count++;
  36.         n >>= 1;
  37.     }
  38.     return count;
  39. }
  40.  
  41. int main() {
  42.     using namespace std;
  43.     string str;
  44.     getline(cin, str);
  45.     vector<myMapNode> vec;
  46.     for (auto letter: str) {
  47.         addLetter(vec, letter);
  48.     }
  49.  
  50.     int bitCount = bitsCount(vec.size() - 1); // find max count of bits in out last index in array
  51.  
  52.     for (int i = 0; i < vec.size(); ++i) {
  53.         vec[i].bitRepr = convertToBin(bitCount, i);
  54.         cout << vec[i].letter << " - " << vec[i].count << " - " << vec[i].bitRepr << '\n';
  55.     }
  56.    
  57.     for (auto letter: str) { // print our string by finding in array equal letters
  58.         for (int j = 0; j < vec.size(); j++) {
  59.             if (vec[j].letter == letter) {
  60.                 cout << vec[j].bitRepr;
  61.             }
  62.         }
  63.     }
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement