root/lang/ruby/misc/brainfuck.rb @ 466

Revision 151, 0.7 kB (checked in by cho45, 6 years ago)

lang/ruby/misc/brainfuck.rb:

Brainfuck インタプリタ on ruby

  • Property svn:executable set to *
Line 
1#!/usr/bin/env ruby
2=begin
3A Brainfuck Interpreter
4
5Public Domain
6=end
7
8arr = []
9ptr = 0
10
11soc = ARGF.read
12pos = 0
13
14while soc.size > pos
15        print soc[pos].chr if $DEBUG
16        p arr if $DEBUG
17       
18        arr[ptr] ||= 0
19       
20        case soc[pos]
21        when ?>
22                ptr += 1
23        when ?<
24                ptr -= 1
25        when ?+
26                arr[ptr] += 1
27        when ?-
28                arr[ptr] -= 1
29        when ?.
30                print arr[ptr].chr
31        when ?,
32                arr[ptr] = $stdin.getc
33        when ?[
34                if arr[ptr].zero?
35                        n = 1
36                        while n.nonzero?
37                                pos += 1
38                                case soc[pos]
39                                when ?[
40                                        n += 1
41                                when ?]
42                                        n -= 1
43                                end
44                        end
45                end
46        when ?]
47                n = -1
48                while n.nonzero?
49                        pos -= 1
50                        case soc[pos]
51                        when ?[
52                                n += 1
53                        when ?]
54                                n -= 1
55                        end
56                end
57                pos -= 1
58        when ??
59                puts arr.inspect + " ptr=#{ptr}"
60        end
61        pos += 1
62end
63puts
64
Note: See TracBrowser for help on using the browser.