Skip to content

Instantly share code, notes, and snippets.

@youchan
Last active February 7, 2025 10:51
Show Gist options
  • Save youchan/2f761c9b93c57006827cccdc1377d526 to your computer and use it in GitHub Desktop.
Save youchan/2f761c9b93c57006827cccdc1377d526 to your computer and use it in GitHub Desktop.
def make_jump_table(prog)
pc = 0
jump_table = {}
stack = []
while pc < prog.size
case prog[pc]
when ?[
stack.push pc
when ?]
raise '対応する[がない' if stack.empty?
start = stack.pop
jump_table[start] = pc
end
pc+=1
end
raise '対応するい]がない' unless stack.empty?
jump_table
end
buf=Array.new(100, 0)
ptr=0
prog=File.read(ARGV.first)
pc=0
jump_table = make_jump_table(prog)
stack = []
while pc < prog.size
ch = prog[pc]
case ch
when ?>
ptr+=1
pc+=1
when ?<
ptr-=1
pc+=1
when ?+
buf[ptr] += 1
pc+=1
when ?-
buf[ptr] -= 1
pc+=1
when ?.
print [buf[ptr]].pack('c')
pc+=1
when ?,
# fall through
pc+=1
when ?[
if buf[ptr]==0
pc = jump_table[pc] + 1
else
stack.push pc
pc+=1
end
when ?]
pc = stack.pop
when ?\n,' '
pc+=1
else
raise "Invalid char: #{ch}."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment