-----
For instance, if you are older you have less time to recover from any major losses, and you may well wish to boost your pension income.
So preserving your capital and generating extra income are your main priorities.
-----
继续来自 M. Hiroi 的 Common Lisp 内容。
最近看的这节讲的是用“生成检验法”来求解一个问题叫“小町算”。
生成检验法就是生成所有可能的解,然后检验并去除那些不可能的,余下的就是正解。
小町算在这节里定义的是这样一个问题:列出由1~9 的 9个数字各一个,组成的三个三位奇数中,所有和为 999 的组合。
1)三个数完成以后才进行检验的代码
(defun komathi-solve1 ()
(defun exam (a b c)
(if (and (oddp a)
(oddp b)
(oddp c)
(< a b c)
(= (+ a b c) 999))
(format t "~D + ~D + ~D = 999~%" a b c)))
(defun make (&optional (numset '(0))
(count 0)
(numlist '(1 2 3 4 5 6 7 8 9)))
(if (= (length numlist) 0)
(exam (car numset) (cadr numset) (caddr numset))
(dolist (x numlist)
(cond
((= count 3) (make (cons x numset)
(1+ count)
(remove x numlist)))
((= count 6) (make (cons x numset)
(1+ count)
(remove x numlist)))
(t (make (cons (+ x (* 10 (car numset))) (cdr numset))
(1+ count)
(remove x numlist)))))))
(make)
)
执行时间是
Evaluation took:
0.191 seconds of real time
0.193173 seconds of total run time (0.188826 user, 0.004347 system)
[ Run times consist of 0.013 seconds GC time, and 0.181 seconds non-GC time. ]
101.05% CPU
475,786,821 processor cycles
132,523,088 bytes consed