#lang racket ; Întoarce 1 dacă celula există și este vie (define (count grid row col max-row max-col) (if (and (>= row 0) (<= row max-row) (>= col 0) (<= col max-col) (list-ref (list-ref grid row) col)) 1 0)) ; Numără vecinii vii ai unei celule (define (get-neighbors grid row col) (define max-row (sub1 (length grid))) (define max-col (sub1 (length (first grid)))) (+ (count grid (sub1 row) (sub1 col) max-row max-col) (count grid (sub1 row) col max-row max-col) (count grid (sub1 row) (add1 col) max-row max-col) (count grid row (sub1 col) max-row max-col) (count grid row (add1 col) max-row max-col) (count grid (add1 row) (sub1 col) max-row max-col) (count grid (add1 row) col max-row max-col) (count grid (add1 row) (add1 col) max-row max-col))) ; Determină starea celulei în generația următoare ; - o celulă vie rămâne vie dacă are 2 sau 3 vecini vii ; - o celulă moartă învie dacă are fix 3 vecini vii (define (next-cell-state grid row col) (define current-cell (list-ref (list-ref grid row) col)) (define live-neighbors (get-neighbors grid row col)) (if current-cell ; dacă este vie (or (= live-neighbors 2) (= live-neighbors 3)) (= live-neighbors 3))) ; Determină starea tuturor celulelor în generația următoare (define (next-generation grid) (define rows (length grid)) (define cols (length (first grid))) (map (λ (row) (map (λ (col) (next-cell-state grid row col)) (range cols))) (range rows))) ; Fluxul infinit de generații (define (life-stream initial-grid) (letrec ((life (stream-cons initial-grid (stream-map next-generation life)))) life)) ; Exemplu (define initial-grid '((#f #f #f #f #f) (#f #f #f #t #f) (#f #t #f #t #f) (#f #f #t #t #f) (#f #f #f #f #f))) (define first-10-generations (stream->list (stream-take (life-stream initial-grid) 10))) ; Afișare (define (print-grid grid) (for ((row grid)) (for ((cell row)) (printf "~a " (if cell "x" "."))) (newline))) (define (print evolution) (for ((gen evolution)) (print-grid gen) (newline))) (print first-10-generations)