2014年1月21日 星期二

LZW解碼(dictionary decoding)

延續上一篇文章
此程式為解碼用

BEGIN
s = NIL;
while not EOF
{
      k = next input code;
      entry = dictionary entry for k;
      if (entry == NULL) 
           entry = s + s[0];
      output entry;
      if (s != NIL)
           add string s + entry[0] to dictionary with a new code;
      s = entry;
}
END

input = 1 4 4 2 7 3 3
s         k       entry/output     code        string
--------------------------------------
                                                   1               A
                                                   2               B
                                                   3               C
--------------------------------------
NIL     1              A
A         4              A                    4                AA
A         4             AA                   5               AA
AA      2              B                     6               AAB
B         7              BB                  7                BB
BB      3              C                     8               BBC
C         3               C                    9               CC
C        eof

output = AAAABBBCC

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main( void )
{
    vector<int> code;            //向量code儲存碼 
    vector<string> str;          //向量str儲存string 
     
    string input,s,entry;
    char c;
    int j,i=1,search_result,k;
    stringstream input_num;
    
    fstream file1,file2;
    file1.open("input.txt");     //input為檔案資料輸入 
    file2.open("output.txt");    //output為檔案資料輸出 
    
    if(!file1 || !file2)
       cout << "檔案開啟失敗";     
    
    //先將A B C 寫入字典 
    str.push_back("A");
    code.push_back(1);
    str.push_back("B");
    code.push_back(2);
    str.push_back("C");
    code.push_back(3);
    
    //解碼開始 
    while(1)
    {
        while(1)  //讀取code 直到遇到空白停下 
        {    
           c = file1.get();
           if( c == ' ' || file1.eof() )
              break;                  
           else   
              input = input + c;     
        }    
        input_num << input;    //進行string轉成int的轉換 
        input_num >> k;
        input_num.clear();
        input.clear();
        
        search_result = 0;
        for(j=0;j<str.size();j++)
        {
            if( k == code[j] )
            {    
                search_result = 1;   //字典裡已有這個碼     
                entry = str[j];              
                break;
            }            
        }                             
        if( search_result == 0 )      //字典裡沒有這個碼   
            entry = s + s[0];  
        file2 << entry;  
        if( i != 1 ) 
        {
            str.push_back(s+entry[0]);
            code.push_back(code.size()+1);
        }  
        i=2;     
        s = entry;
        if(file1.eof())
           break;  
    }   
    //解碼結束 
    system("pause");
    return 0;

沒有留言:

張貼留言