From 2e126db1b80d2ac461721504a5efe82fd679fa96 Mon Sep 17 00:00:00 2001 From: Anjuna-Ramesh <57183849+Anjuna-Ramesh@users.noreply.github.com> Date: Wed, 30 Oct 2019 20:51:05 +0530 Subject: [PATCH] Create lzw --- lzw | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 lzw diff --git a/lzw b/lzw new file mode 100644 index 0000000..738a832 --- /dev/null +++ b/lzw @@ -0,0 +1,82 @@ +#include +using namespace std; +vector encoding(string s1) +{ + cout << "Encoding\n"; + unordered_map table; + for (int i = 0; i <= 255; i++) { + string ch = ""; + ch += char(i); + table[ch] = i; + } + + string p = "", c = ""; + p += s1[0]; + int code = 256; + vector output_code; + cout << "String\tOutput_Code\tAddition\n"; + for (int i = 0; i < s1.length(); i++) { + if (i != s1.length() - 1) + c += s1[i + 1]; + if (table.find(p + c) != table.end()) { + p = p + c; + } + else { + cout << p << "\t" << table[p] << "\t\t" + << p + c << "\t" << code << endl; + output_code.push_back(table[p]); + table[p + c] = code; + code++; + p = c; + } + c = ""; + } + cout << p << "\t" << table[p] << endl; + output_code.push_back(table[p]); + return output_code; +} + +void decoding(vector op) +{ + cout << "\nDecoding\n"; + unordered_map table; + for (int i = 0; i <= 255; i++) { + string ch = ""; + ch += char(i); + table[i] = ch; + } + int old = op[0], n; + string s = table[old]; + string c = ""; + c += s[0]; + cout << s; + int count = 256; + for (int i = 0; i < op.size() - 1; i++) { + n = op[i + 1]; + if (table.find(n) == table.end()) { + s = table[old]; + s = s + c; + } + else { + s = table[n]; + } + cout << s; + c = ""; + c += s[0]; + table[count] = table[old] + c; + count++; + old = n; + } +} +int main() +{ + + string s = "WYS*WYGWYS*WYSWYSG"; + vector output_code = encoding(s); + cout << "Output Codes are: "; + for (int i = 0; i < output_code.size(); i++) { + cout << output_code[i] << " "; + } + cout << endl; + decoding(output_code); +}