哈弗曼编码解码

简介:

#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,如需转载请自行联系原作者

相关文章
|
25天前
|
存储 编解码 数据处理
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码(二)
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码
33 0
|
25天前
|
存储 编解码 数据处理
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码(三)
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码
26 0
|
25天前
|
存储 缓存 编解码
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码(一)
【FFmpeg 视频基本格式】深入理解FFmpeg:从YUV到PCM,解码到编码
36 0
|
9月前
|
存储 Java 数据安全/隐私保护
什么是编码和解码
什么是编码和解码
193 0
|
12月前
|
API 内存技术
FFmpeg连载4-音频解码
ffmpeg连载系列
113 0
|
数据采集 传感器 编解码
【Android RTMP】音频数据采集编码 ( FAAC 编码器编码 AAC 音频解码信息 | 封装 RTMP 音频数据头 | 设置 AAC 音频数据类型 | 封装 RTMP 数据包 )
【Android RTMP】音频数据采集编码 ( FAAC 编码器编码 AAC 音频解码信息 | 封装 RTMP 音频数据头 | 设置 AAC 音频数据类型 | 封装 RTMP 数据包 )
201 0
解码H264帧要注意的两个问题
解码H264帧要注意的两个问题
192 0
|
算法 Apache 数据安全/隐私保护