計算機プログラムの構造と解釈[第2版]
(翔泳社)
ハロルド エイブルソン (著) ジュリー サスマン (著)
ジェラルド・ジェイ サスマン (著)
Harold Abelson (原著) Julie Sussman (原著)
Gerald Jay Sussman (原著) 和田 英一 (翻訳)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Scheme (プログラミング言語)
- kscheme, Gauche (処理系)
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.2(階層データ構造と閉包性)、2.2.1(並びの表現)、問題 2.19.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
- Scheme手習い
問題 2.19.
コード(BBEdit, Emacs)
(define us-coins (list 50 25 10 5 1))
(define us-coins1 (list 1 5 10 25 50))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
(define uk-coins1 (list 0.5 1 2 5 10 20 50 100))
(define cc
(lambda (amount coin-values)
(if (= amount 0)
1
(if (< amount 0)
0
(if (no-more? coin-values)
0
(+ (cc amount
(except-first-denomination coin-values))
(cc (- amount
(first-denomination coin-values))
coin-values)))))))
(define first-denomination
(lambda (coin-values)
(car coin-values)))
(define except-first-denomination
(lambda (coin-values)
(cdr coin-values)))
(define no-more?
(lambda (coin-values)
(null? coin-values)))
;; リストcoin-valuesの順は、ccの答えには影響ないが、計算量には影響がある
;; 大きい硬貨の値を先に引いたほうが、残りの調べる場合の数が少なくて、計算量が少なくて済む
(cc 100 us-coins)
(cc 100 us-coins1)
(cc 50 uk-coins)
(cc 50 uk-coins1)
入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))
$ kscheme < sample19.scm In : Out: us-coins ;(total-pushes = 17 maximum-depth = 8) In : Out: us-coins1 ;(total-pushes = 17 maximum-depth = 8) In : Out: uk-coins ;(total-pushes = 26 maximum-depth = 8) In : Out: uk-coins1 ;(total-pushes = 26 maximum-depth = 8) In : Out: cc ;(total-pushes = 3 maximum-depth = 3) In : Out: first-denomination ;(total-pushes = 3 maximum-depth = 3) In : Out: except-first-denomination ;(total-pushes = 3 maximum-depth = 3) In : Out: no-more? ;(total-pushes = 3 maximum-depth = 3) In : Out: 292 ;(total-pushes = 569053 maximum-depth = 325) In : Out: 292 ;(total-pushes = 1353020 maximum-depth = 325) In : ;begin garbage collection: 10000000 ;end garbage collection: 380 Out: 6149 ;(total-pushes = 9959785 maximum-depth = 337) In : ;begin garbage collection: 10000000 ;end garbage collection: 351 ;begin garbage collection: 10000000 ;end garbage collection: 357 ;begin garbage collection: 10000000 ;end garbage collection: 394 ;begin garbage collection: 10000000 ;end garbage collection: 447 ;begin garbage collection: 10000000 ;end garbage collection: 425 ;begin garbage collection: 10000000 ;end garbage collection: 445 ;begin garbage collection: 10000000 ;end garbage collection: 509 Out: 6149 ;(total-pushes = 41077533 maximum-depth = 337) In : $
0 コメント:
コメントを投稿