Advertisement
Guest User

WBS Adaptiv

a guest
Jan 20th, 2019
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. /**
  6.  * Verifica daca toate caracterele din block sunt egale cu bit.
  7.  */
  8. bool allOf(const std::string & block, char bit) {
  9.     for(const auto & c : block) {
  10.         if (c != bit) return false;
  11.     }
  12.     return true;
  13. }
  14.  
  15. /**
  16.  * Neaga bitul bit.
  17.  */
  18. char rev(char bit) {
  19.     return bit == '0' ? '1' : '0';
  20. }
  21.  
  22. /*
  23.  * Codeaza blocul code care ar trebui sa aiba lungimea maxima blockLength, folosind codul bit.
  24.  */
  25. std::string encode(const std::string & code, uint32_t blockLength, char bit) {
  26.     std::string result;
  27.     result.push_back(bit);
  28.     for(uint32_t i = 0; i < code.length(); i += blockLength) {
  29.         std::string currentBlock = code.substr(i, blockLength);
  30.         if(currentBlock.length() != blockLength || !allOf(currentBlock, bit)) {
  31.             result += rev(bit) + currentBlock;
  32.         } else {
  33.             result += bit;
  34.         }
  35.     }
  36.     return result;
  37. }
  38.  
  39. int main() {
  40.     uint32_t length;
  41.     uint32_t block;
  42.     std::cin >> length >> block;
  43.     std::string bits;
  44.     /* Si citeste caracter cu caracter si se concateneaza in string-ul bits.*/
  45.     while(length--) {
  46.         char bit;
  47.         std::cin >> bit;
  48.         bits.push_back(bit);
  49.     }
  50.  
  51.     std::string option1 = encode(bits, block, '0');
  52.     std::string option2 = encode(bits, block, '1');
  53.  
  54.     /* Alegem varianta mai buna */
  55.     if(option2.length() < option1.length()) {
  56.         option1 = option2;
  57.     }
  58.  
  59.     /* Se afiseza raportul de compresie si apoi secventa codata, caracter cu caracter */
  60.     std::cout << std::setprecision(2) << std::fixed << (double)bits.length() / option1.length() << std::endl;
  61.     for(const auto & c : option1) std::cout << c << std::endl;
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement