哈弗曼编码解码

简介:

#lang scheme

( define nil '() )

( define ( make-leaf symbol weight )
   ( list 'leaf symbol weight ) )  

( define ( leaf?

obj )
   ( eq?

( car obj ) 'leaf ) )

( define ( symbol-leaf x )
   ( cadr x ) )

( define ( weight-leaf x )
   ( caddr x ) )

( define ( make-code-tree left right )
   ( list left 
          right 
          ( append ( symbols left )
                   ( symbols right ) )
          ( + ( weight left )
              ( weight right ) ) ) )

( define ( left-branch tree )
   ( car tree ) )

( define ( right-branch tree )
   ( cadr tree ) )

( define ( symbols tree )
   ( cond [ ( leaf? tree )
            ( list ( symbol-leaf tree ) ) ]
          [ else ( caddr tree ) ] ) )

( define ( weight tree )
   ( cond [ ( leaf?

tree )
            ( weight-leaf tree ) ]
          [ else ( cadddr tree ) ] ) )  

( define ( decode bits tree )
   ( define ( decode-1 bits cur-branch )
      ( cond [ ( null?

bits ) nil ]
             [ else ( let ( [ next-branch 
                              ( choose-branch ( car bits ) cur-branch ) ] )
                       ( cond [ ( leaf?

next-branch )
                                ( cons ( symbol-leaf next-branch )
                                       ( decode-1 ( cdr bits ) tree ) ) ]
                              [ decode-1 ( cdr bits ) next-branch ] ) ) ] ) )
   ( decode-1 bits tree ) )

( define ( choose-branch bit branch )
   ( cond [ ( = bit 0 )
            ( left-branch branch ) ]
          [ ( = bit 1 )
            ( right-branch branch ) ]
          [ else ( error "Pass" ) ] ) )

( define sample-tree 
   ( make-code-tree ( make-leaf 'A 4 )
                    ( make-code-tree ( make-leaf 'B 2 )
                                     ( make-code-tree ( make-leaf 'D 1 )
                                                      ( make-leaf 'C 1 ) ) ) ) )

( define sample-message '( 0 1 1 0 0 1 0 1 0 1 1 1 0 ) )

( decode sample-message sample-tree )





本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5256645.html,如需转载请自行联系原作者

相关文章
|
8天前
|
机器学习/深度学习 人工智能 自然语言处理
编码和解码的未来之路
编码和解码的未来之路
|
10月前
|
存储 Java 数据安全/隐私保护
什么是编码和解码
什么是编码和解码
199 0
|
API 内存技术
FFmpeg连载4-音频解码
ffmpeg连载系列
116 0
|
前端开发 JavaScript
前端实现 base64 编码和解码
前端实现 base64 编码和解码
426 0
前端实现 base64 编码和解码
|
Java
小程序中base64解码/编码
很多人都在为小程序如何实现base64编码/解码困扰,于是我参考前端大佬们对JavaScript中实现base64的文章进行了改写。简单实现了一个。。希望能帮助到小程序开发一线的大家吧、 不多说直接上代码: /** * UTF16和UTF8转换对照表 * U+00000000 – U+000000...
4737 1
解码H264帧要注意的两个问题
解码H264帧要注意的两个问题
193 0
|
算法 Apache 数据安全/隐私保护