Comment detail

ライフゲーム (Nested Flatten)

初めて投稿します。 よろしくお願いします。 普段はC++を扱う事が多いのですが、趣味でSchemeを勉強しています。 書き方が変なところなどがあれば、ご指摘くださいませ。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(use srfi-1)
(use srfi-27)
(use srfi-43)

;;主手続き
(define (life-game n t)
  (let loop ((board (make-initial-board n))
             (count 0))
    (if (= count t)
        #f
        (begin
          (display-life-game board n)
          (loop (next-step board n) (+ count 1))))))

;;画面出力
(define (display-life-game board n)
  (begin
    (vector-for-each (lambda (position state)
                  (if (= (remainder (+ position 1) n) 0)
                      (print state)
                      (display state)))
                board)
    (newline)))

;;初期の盤面を作成
;;ランダムな盤面を作成
(define (make-initial-board n)
  (let1 board (make-vector (* n n) 0)
    (vector-map (lambda (x y)
                  (random-integer 2))
                board)))

;;盤面を更新
(define (next-step board size)
  (vector-map (lambda (loc stat)
                (state-change-rule stat
                                   (fold +
                                         0
                                         (map (pa$ vector-ref board)
                                              (neighbor-cell loc size)))))
              board))

;;状態を変えるルール
(define (state-change-rule self neighbor-sum)
  (if (= self 0)
      (if (= neighbor-sum 3)
          1
          0)
      (if (or (= neighbor-sum 2) (= neighbor-sum 3))
          1
          0)))

;;近傍セルを取得
(define (neighbor-cell r size)
  (define (boundary-check x)
    (cond ((< x 0) (+ x size))
          ((>= x size) (- x size))
  (define (make-coodinate-change-proc x y)
    (lambda (offset)
      (+ (boundary-check (+ x (car offset)))
         (* (boundary-check (- y (cdr offset)))
            size))))

  (receive (y x) (quotient&remainder r size)
    (map (make-coodinate-change-proc x y)
         (list (cons 1 0)
               (cons 1 -1)
               (cons 0 -1)
               (cons -1 -1)
               (cons -1 0)
               (cons -1 1)
               (cons 0 1)
               (cons 1 1)))))

Index

Feed

Other

Link

Pathtraq

loading...