Execute Brain****
1
define tape_length = 50_000;
2
define eof_val = -1;
3
define unbalanced_exit_code = 1;
4
5
var cmd = 0;
6
var cell = 0;
7
var code = [];
8
var loops = [];
9
var tape = tape_length.of(0);
10
11
func get_input {
12
static input_buffer = [];
13
input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord}));
14
input_buffer.shift \\ eof_val;
15
}
16
17
func jump {
18
var depth = 0;
19
while (depth >= 0) {
20
++cmd < code.len || Sys.exit(unbalanced_exit_code);
21
if (code[cmd] == '[') {
22
++depth;
23
}
24
elsif (code[cmd] == ']') {
25
--depth;
26
}
27
}
28
}
29
30
var commands = Hash.new(
31
'>' => { ++cell },
32
'<' => { --cell },
33
'+' => { ++tape[cell] },
34
'-' => { --tape[cell] },
35
'.' => { tape[cell].chr.print },
36
',' => { tape[cell] = get_input() },
37
'[' => { tape[cell] ? loops.append(cmd) : jump() },
38
']' => { cmd = (loops.pop - 1) },
39
);
40
41
STDOUT.autoflush(1);
42
code = ARGF.slurp.chars.grep {|c| commands.exists(c)};
43
var code_len = code.len;
44
45
while (cmd < code_len) {
46
commands{code[cmd]}.run;
47
cmd++;
48
}
Copied!
Last modified 1yr ago
Copy link