1

これがLempel-Ziv-Welch圧縮の擬似コードです。

 pattern = get input character
 while ( not end-of-file ) {
     K = get input character
     if ( <<pattern, K>> is NOT in 
             the string table ){
         output the code for pattern
         add <<pattern, K>> to the string table
         pattern = K
     }
     else { pattern = <<pattern, K>> }
 }
 output the code for pattern
 output EOF_CODE

これをLuaでコーディングしようとしていますが、実際には機能していません。これがPythonのLZW関数をモデルにしたコードですが、8行目に「文字列値を呼び出そうとしました」というエラーが表示されます。

 function compress(uncompressed)

 local dict_size = 256
 local dictionary = {}

 w = ""
 result = {}
 for c in uncompressed do
  -- while c is in the function compress
     local wc = w + c
     if dictionary[wc] == true then
         w = wc
     else
         dictionary[w] = ""
         -- Add wc to the dictionary.
         dictionary[wc] = dict_size
         dict_size = dict_size + 1
         w = c
    end
 -- Output the code for w.
 if w then
   dictionary[w] = ""
 end
 end
 return dictionary
 end

 compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
 print (compressed)

コードを実行するか、LuaでLZW圧縮をコーディングするのを手伝ってもらいたいです。どうもありがとう!

4

2 に答える 2

2

Lua での高性能 LZW 圧縮アルゴリズムのソースをダウンロードするには、こちらも参照してください。

于 2012-07-31T16:48:10.097 に答える
2

が文字列であると仮定するuncompressedと、次のようなものを使用して反復する必要があります。

for i = 1, #uncompressed do
  local c = string.sub(uncompressed, i, i)
  -- etc
end   

10 行目に別の問題があります。..は Lua の文字列連結に使用されるため、この行はlocal wc = w .. c.

文字列連結のパフォーマンスに関して、これを読むこともできます。簡単に言うと、多くの場合、各要素をテーブルに保持して で返す方が効率的table.concat()です。

于 2012-07-31T16:28:33.883 に答える