1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

function parse_parens(code)
  pos_open = [i for (i, c) in enumerate(code) if c  == '[']
  pos_close = [i for (i, c) in enumerate(code) if c  == ']']
  if length(pos_open) != length(pos_close)
    error("parenthesis mismatch")
  end
  dict_parenspos = Dict(zip(pos_open, reverse(pos_close)))
  return dict_parenspos
end


function brainfuck(code)
  tape = zeros(Int, 30_000)
  tape_ptr = 1
  code_ptr = 1
  dict_parenspos = parse_parens(code)
  stack = []

  while code_ptr < length(code)
    c = code[code_ptr]

    if c == '[' && tape[tape_ptr] == 0
      code_ptr = dict_parenspos[tape_ptr]
    elseif c == '[' && tape[tape_ptr] != 0
      push!(stack, code_ptr)

    elseif c == ']' && tape[tape_ptr] == 0
      pop!(stack)
    elseif c == ']' && tape[tape_ptr] != 0
      code_ptr = pop!(stack) - 1

    elseif c == '>'
      if 30_000 <= tape_ptr
          error("Segmentation fault")
      end
      tape_ptr += 1
    elseif c == '<'
      if tape_ptr <= 0
          error("Segmentation fault")
      end
      tape_ptr -= 1

    elseif c == '+'
      tape[tape_ptr] = mod(tape[tape_ptr] + 1, 256)
    elseif c == '-'
      tape[tape_ptr] = mod(tape[tape_ptr] - 1, 256)
    elseif c == '.'
      print( Char(tape[tape_ptr]) )
    end

    code_ptr += 1
  end
end


code = """
  +++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.
  ------------.<++++++++.--------.+++.------.--------.>+.
  """

brainfuck(code)

こんな感じでしょうか。

参考資料

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?