Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PlacementTestPlaygrounds.cpp : This file contains the 'main' function. Program execution begins and ends there.
- //Timo Nys
- //16-11-2019
- #include "pch.h"
- #include <iostream>
- #include <iomanip>
- #include <fstream>
- #include <string>
- std::string RunLengthCompress(const std::string& word);
- float CalculateCompressionRatio(int originalCount, int newCount);
- int main()
- {
- std::ifstream fileToEncode;
- std::string fileName;
- //Prompt the user for a VALID filename to compress
- do
- {
- std::cout << "Give the name of file to be encoded. \n";
- std::cin >> fileName;
- fileToEncode.open(fileName + ".txt");
- } while (!fileToEncode.is_open());
- //Prompt the user how to name the file to compress to
- std::cout << "Give the name of file to write the compressed result to. \n";
- std::cin >> fileName;
- std::ofstream fileToCompressTo{ fileName + ".txt" };
- //Compress every word in the file
- std::string wordToEncode;
- if (fileToEncode.is_open())
- {
- int originalLetterCount{ 0 };
- int newLetterCount{ 0 };
- while (fileToEncode >> wordToEncode)
- {
- originalLetterCount += wordToEncode.length();
- std::string compressedResult = RunLengthCompress(wordToEncode);
- fileToCompressTo << compressedResult << ' '; //Parse the compressed result to the compressed file and add a space between individual words
- newLetterCount += compressedResult.length() ;
- }
- //Print the compression rate
- float compressionRatio = CalculateCompressionRatio(originalLetterCount, newLetterCount);
- std::cout << std::setprecision(4) << compressionRatio;
- }
- return 0;
- }
- std::string RunLengthCompress(const std::string& word)
- {
- std::string compressed{ "" };
- std::string toCompress{ word };//cache it in local memory
- size_t wordLength = word.length();
- for (size_t i = 0; i < wordLength; ++i)
- {
- int amount{ 1 };//init at 1 cause the character/number will always appear at least once
- while (i < wordLength - 1 && toCompress[i] == toCompress[i + 1])
- {
- ++amount;
- ++i;
- }
- compressed += std::to_string(amount) + toCompress[i];
- }
- return compressed;
- }
- float CalculateCompressionRatio(int originalCount, int newCount)
- {
- return float(originalCount) / float(newCount);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement