2014年10月13日月曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の4(超言語的抽象)、4.3(Schemeの変形 - 非決定性計算)、4.3.3(非決定性プログラムの例)、論理パズル、問題 4.41.を解いてみる。

その他参考書籍

問題 4.41.

コード(BBEdit, Emacs)

sample41.scm

#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-

(define (distinct? items)
  (cond ((null? items) #t)
        ((null? (cdr items)) #t)
        ((member (car items) (cdr items)) #f)
        (else (distinct? (cdr items)))))

(define (multiple-dwelling)
  (define (inner baker cooper fletcher miller smith)
    (and (not (= fletcher 1))
         (not (= fletcher 5))
         (not (= baker 5))
         (not (= cooper 1))
         (> miller cooper)
         (not (= (abs (- smith fletcher)) 1))
         (not (= (abs (- fletcher cooper)) 1))
         (distinct? (list baker cooper fletcher miller smith))))

  (define (iter list-of-list)
    (if (null? list-of-list)
        '()
        (let ((items (car list-of-list)))
          (if (inner (car items)
                     (cadr items)
                     (caddr items)
                     (cadddr items)
                     (car (cddddr items)))
              (cons (list (list 'baker (car items))
                          (list 'cooper (cadr items))
                          (list 'fletcher (caddr items))
                          (list 'miller (cadddr items))
                          (list 'smith (car (cddddr items))))
                    (iter (cdr list-of-list)))
              (iter (cdr list-of-list))))))
  (define (make-list-of-list list-of-list)
    (if (null? list-of-list)
        '()
        (let ((first (car list-of-list))
              (rest (cdr list-of-list)))
          (cond ((null? first) '())
                ((null? rest)
                 (map list
                      first))
                (else
                 (append (map (lambda (items)
                                (cons (car first)
                                      items))
                              (make-list-of-list rest))
                         (make-list-of-list (cons (cdr first)
                                                  rest))))))))
  (iter
   (make-list-of-list
    (list (list 1 2 3 4 5)
          (list 1 2 3 4 5)
          (list 1 2 3 4 5)
          (list 1 2 3 4 5)
          (list 1 2 3 4 5)))))

(print (multiple-dwelling))

入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))

$ ./sample41.scm 
(((baker 3) (cooper 2) (fletcher 4) (miller 5) (smith 1)))
$

0 コメント:

コメントを投稿