Skip to content

Instantly share code, notes, and snippets.

@koropicot
Created April 5, 2013 10:04
Show Gist options
  • Save koropicot/5318135 to your computer and use it in GitHub Desktop.
Save koropicot/5318135 to your computer and use it in GitHub Desktop.
単純なBrainf*ckインタプリタ
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace SimpleBF
{
class Program
{
static void Main(string[] args)
{
//標準入出力から
//var reader = Console.In;
//文字列から
var input = "5";
var reader = new StringReader(input);
//http://golf.shinh.org/p.rb?identity+matrix のコード
//(あなごるでは入力の最後に無駄な文字が入ってたのでこのままでは動きません)
var rawCode =
@">>,+[->,+]>++++[->++++<]>[-<++<+++<---<[[-<+>]<--->]<[->+<]>>>>>]<<<<[->++++++++++<]
>[->>>[-<<.>.>>+<]+<<+.->>>[-<+>]<<<<[->>.<.<<+>]<[->+<]++++++++++.[-]>]";
var mem = new int[1024];
var mc = 0;
var pc = 0;
var code = rawCode.Where(c=>"[]+-><.,".Contains(c)).ToArray();
while (pc < code.Length)
{
switch (code[pc])
{
case '>':
mc++; break;
case '<':
mc--; break;
case '+':
mem[mc]++; break;
case '-':
mem[mc]--; break;
case '[':
if (mem[mc] == 0)
{
pc++;
for (var i = 1; i > 0; pc++)
{
if (code[pc] == '[')
i++;
if (code[pc] == ']')
i--;
}
pc--;
}
break;
case ']':
pc--;
for (var i = 1; i > 0; pc--)
{
if (code[pc] == ']')
i++;
if (code[pc] == '[')
i--;
}
break;
case '.':
Console.Write((char)mem[mc]); break;
case ',':
mem[mc] = reader.Read();; break;
}
pc++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment