Advertisement
Guest User

Untitled

a guest
Nov 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. // PlacementTestPlaygrounds.cpp : This file contains the 'main' function. Program execution begins and ends there.
  2. //Timo Nys
  3. //16-11-2019
  4.  
  5. #include "pch.h"
  6. #include <iostream>
  7. #include <iomanip>
  8. #include <fstream>
  9. #include <string>
  10.  
  11. std::string RunLengthCompress(const std::string& word);
  12. float CalculateCompressionRatio(int originalCount, int newCount);
  13.  
  14. int main()
  15. {
  16. std::ifstream fileToEncode;
  17. std::string fileName;
  18. //Prompt the user for a VALID filename to compress
  19. do
  20. {
  21. std::cout << "Give the name of file to be encoded. \n";
  22. std::cin >> fileName;
  23.  
  24. fileToEncode.open(fileName + ".txt");
  25.  
  26. } while (!fileToEncode.is_open());
  27.  
  28. //Prompt the user how to name the file to compress to
  29. std::cout << "Give the name of file to write the compressed result to. \n";
  30. std::cin >> fileName;
  31. std::ofstream fileToCompressTo{ fileName + ".txt" };
  32.  
  33. //Compress every word in the file
  34. std::string wordToEncode;
  35.  
  36. if (fileToEncode.is_open())
  37. {
  38. int originalLetterCount{ 0 };
  39. int newLetterCount{ 0 };
  40. while (fileToEncode >> wordToEncode)
  41. {
  42. originalLetterCount += wordToEncode.length();
  43. std::string compressedResult = RunLengthCompress(wordToEncode);
  44. fileToCompressTo << compressedResult << ' '; //Parse the compressed result to the compressed file and add a space between individual words
  45. newLetterCount += compressedResult.length() ;
  46.  
  47. }
  48. //Print the compression rate
  49. float compressionRatio = CalculateCompressionRatio(originalLetterCount, newLetterCount);
  50. std::cout << std::setprecision(4) << compressionRatio;
  51. }
  52.  
  53. return 0;
  54. }
  55.  
  56. std::string RunLengthCompress(const std::string& word)
  57. {
  58. std::string compressed{ "" };
  59. std::string toCompress{ word };//cache it in local memory
  60. size_t wordLength = word.length();
  61.  
  62. for (size_t i = 0; i < wordLength; ++i)
  63. {
  64. int amount{ 1 };//init at 1 cause the character/number will always appear at least once
  65. while (i < wordLength - 1 && toCompress[i] == toCompress[i + 1])
  66. {
  67. ++amount;
  68. ++i;
  69. }
  70. compressed += std::to_string(amount) + toCompress[i];
  71. }
  72. return compressed;
  73. }
  74.  
  75. float CalculateCompressionRatio(int originalCount, int newCount)
  76. {
  77. return float(originalCount) / float(newCount);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement