A simple program with complex behaviour

Arjen Markus (19 july 2010) As demonstrated by Stephen Wolfram [1 ], very simple programs can exhibit very complex behaviour. Here is a small example (the code is not as nice as it could have been, I did not want to spend too much time ;)).

The output when viewed as bit patterns seems to be random with no discernible patterns - viewing them as numbers reveals a much clearer picture - I will leave that as an exercise ;). And I intend to get the book from the library when I am back from my holidays.

# wolfram.tcl --
#     Automaton producing seemingly random output
#
proc step {} {
    global program memory position last

    foreach {cmd reg label} $program($position) {
        if { $cmd eq "INCR" } {
            incr memory($reg)
            incr position
        } elseif { $cmd eq "DECJ" } {
            if { $memory($reg) > 0 } {
                incr memory($reg) -1
                set position $label
            } else {
                incr position
            }
        }
        if { $position > $last } {
            set position 0
        }

        puts "$memory(1) $memory(2)"
    }
}

# main --
#
set position    0
set memory(1)   0
set memory(2)   0
set program(0) {INCR 1}
set program(1) {INCR 1}
set program(2) {INCR 1}
set program(3) {DECJ 2 0}
set program(4) {DECJ 1 5}
set program(5) {INCR 2}
set program(6) {DECJ 1 4}
set program(7) {DECJ 1 2}
set last 7

for { set i 0 } { $i < 1000 } { incr i } {
    step
}