Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 19.03.2013, 23:36   #1
803
Пользователь
 
Регистрация: 13.02.2012
Сообщений: 89
По умолчанию Архиватор LZW (работа с файлами)

Здравствуйте. Есть программа compressed LZW вот код
Код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace LZW.C
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //StreamReader streamReader = new StreamReader("test.txt"); //Открываем файл для чтения
            //string compressed = ""; //Объявляем переменную, в которую будем записывать текст из файла
            //while (!streamReader.EndOfStream) //Цикл длиться пока не будет достигнут конец файла
            //{
            //    compressed += streamReader.ReadLine(); //В переменную str по строчно записываем содержимое файла
            //}
            List<int> compressed = Compress("Your distresses in your journey from Heidelberg to Schaffhausen");
            Console.WriteLine(string.Join(", ", compressed));
            string decompressed = Decompress(compressed);
            Console.WriteLine(decompressed);
            //StreamWriter file3 = new StreamWriter("out.txt");
            //file3.WriteLine(compressed);
            //file3.Close();
        }

        public static List<int> Compress(string uncompressed)
        {
            // build the dictionary
            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
                {
                    // write w to output
                    compressed.Add(dictionary[w]);
                    // wc is a new sequence; add it to the dictionary
                    dictionary.Add(wc, dictionary.Count);
                    w = c.ToString();
                }
            }

            // write remaining output if necessary
            if (!string.IsNullOrEmpty(w))
                compressed.Add(dictionary[w]);

            return compressed;
        }

        public static string Decompress(List<int> compressed)
        {
            // build the dictionary
            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);

                // new sequence; add it to the dictionary
                dictionary.Add(dictionary.Count, w + entry[0]);

                w = entry;
            }

            return decompressed.ToString();
        }
    }
}
У меня возникла 3 вопроса.
1. Правильно ли работает программа (алгоритм) LZW?
2. Как правильно считать информацию из txt файла через StreamReadr? (там есть в коде мои попытки, но они неправильные)
3. Почему когда я вывожу ответ (compressed) в файл у меня выводиться ерунда в место закодированного текста?
Помогите пожалуйста, заранее спасибо.
803 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Архиватор, курсовая работа, assembler ilonka Assembler - Ассемблер (FASM, MASM, WASM, NASM, GoASM, Gas, RosAsm, HLA) и не рекомендуем TASM 3 06.07.2013 14:56
Архивация LZW Начинающий програм Помощь студентам 7 21.11.2012 00:32
Алгоритм сжатия LZW dollemika Помощь студентам 11 20.06.2012 07:40
LZW сжатие. SrgGld Общие вопросы C/C++ 1 19.12.2010 21:39
LZW C++ mephistophel Общие вопросы C/C++ 2 11.04.2010 23:55