zoukankan      html  css  js  c++  java
  • 哈弗曼编码解码


    #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 )




  • 相关阅读:
    上帝永远不会问你的十件事
    discuz x1.5 showmessage函数和showDialog函数解析
    人生,没有那么简单…
    Proxy代理对象是如何调用invoke()方法的.
    实现简单的AOP前置后置增强
    浅谈设计模式visitor访问者模式
    了解jsp,这一篇就够了.
    jsp之el表达式jstl标签
    orale数据库.实例.表空间.用户.表
    题解 UVa10892
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5256645.html
Copyright © 2011-2022 走看看