projects: update some short descriptions
[nit.git] / examples / rosettacode / one_dimensional_cellular_automata.nit
1 #!/usr/bin/env nit
2 #
3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
5
6 # Task: One-dimensional_cellular_automata
7 # SEE: <http://rosettacode.org/wiki/One-dimensional_cellular_automata>
8 module one_dimensional_cellular_automata
9
10 fun evolve(cells: SequenceRead[Char]): SequenceRead[Char]
11 do
12 var res = new Array[Char]
13 for i in [0..cells.length[ do
14 var n = neighboors(i, cells)
15 if cells[i] == '#' then
16 res.add(b_to_char(n == 1))
17 else
18 res.add(b_to_char(n == 2))
19 end
20 end
21 return res
22 end
23
24 fun b_to_char(b: Bool): Char do if b then return '#' else return '_'
25
26 fun neighboors(i: Int, cells: SequenceRead[Char]): Int
27 do
28 var res = 0
29 if i > 0 and cells[i-1] == '#' then res += 1
30 if i < cells.length - 1 and cells[i+1] == '#' then res += 1
31 return res
32 end
33
34 var ary = "_###_##_#_#_#_#__#__".chars
35 loop
36 print ary.join
37 var nxt = evolve(ary)
38 if ary == nxt then break
39 ary = nxt
40 end