rosetta code: one_dimensional_cellular_automata
authorJean Privat <jean@pryen.org>
Wed, 10 Jun 2015 19:52:53 +0000 (15:52 -0400)
committerJean Privat <jean@pryen.org>
Wed, 10 Jun 2015 19:52:53 +0000 (15:52 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

examples/rosettacode/one_dimensional_cellular_automata.nit [new file with mode: 0644]
tests/sav/one_dimensional_cellular_automata.res [new file with mode: 0644]

diff --git a/examples/rosettacode/one_dimensional_cellular_automata.nit b/examples/rosettacode/one_dimensional_cellular_automata.nit
new file mode 100644 (file)
index 0000000..77b2ed2
--- /dev/null
@@ -0,0 +1,40 @@
+#!/usr/bin/env nit
+#
+# This file is part of NIT ( http://www.nitlanguage.org ).
+# This program is public domain
+
+# Task: One-dimensional_cellular_automata
+# SEE: <http://rosettacode.org/wiki/One-dimensional_cellular_automata>
+module one_dimensional_cellular_automata
+
+fun evolve(cells: SequenceRead[Char]): SequenceRead[Char]
+do
+       var res = new Array[Char]
+       for i in [0..cells.length[ do
+               var n = neighboors(i, cells)
+               if cells[i] == '#' then
+                       res.add(b_to_char(n == 1))
+               else
+                       res.add(b_to_char(n == 2))
+               end
+       end
+       return res
+end
+
+fun b_to_char(b: Bool): Char do if b then return '#' else return '_'
+
+fun neighboors(i: Int, cells: SequenceRead[Char]): Int
+do
+       var res = 0
+       if i > 0 and cells[i-1] == '#' then res += 1
+       if i < cells.length - 1 and cells[i+1] == '#' then res += 1
+       return res
+end
+
+var ary = "_###_##_#_#_#_#__#__".chars
+loop
+       print ary.join("")
+       var nxt = evolve(ary)
+       if ary == nxt then break
+       ary = nxt
+end
diff --git a/tests/sav/one_dimensional_cellular_automata.res b/tests/sav/one_dimensional_cellular_automata.res
new file mode 100644 (file)
index 0000000..eb4bb2e
--- /dev/null
@@ -0,0 +1,9 @@
+_###_##_#_#_#_#__#__
+_#_#####_#_#_#______
+__##___##_#_#_______
+__##___###_#________
+__##___#_##_________
+__##____###_________
+__##____#_#_________
+__##_____#__________
+__##________________