Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Lab3
- {
- class Program
- {
- public static void Main(string[] args)
- {
- List<int> compressed = Compress(Console.ReadLine());
- Console.WriteLine(string.Join(", ", compressed));
- string decompressed = Decompress(compressed);
- Console.WriteLine(decompressed);
- var file1 = File.Open("test1.txt", FileMode.Open);
- var file2 = File.Open("test2.txt", FileMode.Open);
- Console.WriteLine($"Size of compressed file: {file1.Length} byte");
- Console.WriteLine($"Size of decompressed file: {file2.Length} byte");
- file1.Dispose();
- file2.Dispose();
- Console.ReadKey();
- }
- public static List<int> Compress(string uncompressed)
- {
- Dictionary<string, int> dictionary = new Dictionary<string, int>();
- for (int i = 0; i < 256; i++)
- dictionary.Add(((char)i).ToString(), i);
- string w = string.Empty;
- List<int> compressed = new List<int>();
- foreach (char c in uncompressed)
- {
- string wc = w + c;
- if (dictionary.ContainsKey(wc))
- {
- w = wc;
- }
- else
- {
- compressed.Add(dictionary[w]);
- dictionary.Add(wc, dictionary.Count);
- w = c.ToString();
- }
- }
- if (!string.IsNullOrEmpty(w))
- compressed.Add(dictionary[w]);
- var array = new StringBuilder();
- foreach(var el in compressed)
- {
- array.Append($"{el.ToString()} ");
- }
- File.WriteAllText("test1.txt", array.ToString());
- return compressed;
- }
- public static string Decompress(List<int> compressed)
- {
- Dictionary<int, string> dictionary = new Dictionary<int, string>();
- for (int i = 0; i < 256; i++)
- dictionary.Add(i, ((char)i).ToString());
- string w = dictionary[compressed[0]];
- compressed.RemoveAt(0);
- StringBuilder decompressed = new StringBuilder(w);
- foreach (int k in compressed)
- {
- string entry = null;
- if (dictionary.ContainsKey(k))
- entry = dictionary[k];
- else if (k == dictionary.Count)
- entry = w + w[0];
- decompressed.Append(entry);
- dictionary.Add(dictionary.Count, w + entry[0]);
- w = entry;
- }
- File.WriteAllText("test2.txt", decompressed.ToString());
- return decompressed.ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement