문제
인코딩 나무와 보기 글을 다음과 같이 정의하라.
(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 ))
문제로 부터 얻은 것
이 문제의 가치는 문제를 실행기에 실행시키는 것이 아닙니다.
symbols와 weight가 트리와 이파리를 구분하는 방법
허프만 트리의 생성 원리
앞가지 코드prefix code 를 사용하는 이유
등의 내용을 잘 이해했고 손으로 코드를 직접 짤 수 있어야 이 문제를 풀었다고 할 수 있습니다.
문제풀이
a. 문제를 푸는데 필요한 프로시저들
(define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car object) 'leaf )) (define (symbol-leaf object) (cadr object)) (define (weight-leaf object) (caddr object)) (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) (if (leaf? tree) (list (symbol-leaf tree)) (caddr tree))) (define (weight tree) (if (leaf? tree) (weight-leaf tree) (cadddr tree))) (define (decode bits tree) (define (decode-inner bits current-branch) (if (null? bits) '() (let ((next-branch (choose-branch (car bits) current-branch))) (if (leaf? next-branch) (cons (symbol-leaf next-branch) (decode-inner (cdr bits) tree)) (decode-inner (cdr bits) next-branch))))) (decode-inner bits tree)) (define (choose-branch bit branch) (cond ((= bit 0 ) (left-branch branch)) ((= bit 1 ) (right-branch branch)) (else (error "Something is wrong in your bits -- CHOOSE BRANCH" ))))
b. 디코딩 결과
(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)
읽어주셔서 감사합니다.