Created
July 21, 2014 07:42
-
-
Save thequux/b94be012ee8cdb0ccf55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sed -rf | |
# How to run: | |
# echo 'A A<1+B1-C>B<1-A1+B>D<1-B1qC> 0<0>0' | |
# Note: Your local sed may use a different flag for "extended" regexes; this is written for GNU sed. | |
# | |
# tape: [active-state] " " (state-name "<" (write move next-state)_0 (write move next-state)_1 ">")* " " tape... "<" curpos ">" tape... | |
# State names can be any character not in " <>". | |
# The tape consists of 0's and 1's. | |
# The "move" field can be "-" to move left, "+" to move right, or "q" to halt. | |
: start | |
# Print out tape | |
h | |
s/ .* / / | |
# If you want pretty colors, you can add | |
s/<(.)>/\x1b[1;32m\1\x1b[0m/ | |
p | |
g | |
# Start by padding the tape if necessary... | |
s/^(. [^ ]* )</\10</ | |
s/>$/>0/ | |
# Identify current state | |
s/^(.) ([^ ]*)\1(<......>)/\3 \2\1\3/ | |
/^[^<]/{ | |
s/^(.) .*/Unknown state \1/ | |
q | |
} | |
# Identify current bit | |
s/^<(...)...> ([^ ]* .*<0>)/\1 \2/ | |
s/^<...(...)> ([^ ]* .*<1>)/\1 \2/ | |
# Write new bit | |
s/^(.)(.. [^ ]* .*<).(>.*)/\2\1\3/ | |
# Move as appropriate. Note that due to earlier padding, we are guaranteed that the move can be made. | |
s/^(-. [^ ]* .*)(.)<(.)>(.)(.*)$/\1<\2>\3\4\5/ | |
s/^(\+. [^ ]* .*)(.)<(.)>(.)(.*)$/\1\2\3<\4>\5/ | |
/^q/{ | |
s/.*/Halted./ | |
q | |
} | |
# Drop move indicator | |
s/^.// | |
# Restart | |
b start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment