C#の練習で実装
brainfuckとは http://dic.nicovideo.jp/a/brainfuck
一部機能は実装してないが、Hello World!出力できたのでよし
入力
+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+.
出力
Hello, world!
コード
brainfuck.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace brainfuck
{
class BrainFuck
{
static int search1(string str, int start)
{
int c = 0;
for (int i = start + 1; i < str.Length; ++i)
{
if (str[i] == '[')
{
c++;
}
if (str[i] == ']')
{
if (c == 0)
{
return i;
}
else
{
c--;
}
}
}
return -1;
}
static int search2(string str, int start)
{
int c = 0;
string rev = new string(str.Reverse().ToArray());
int rev_start = str.Length - start - 1;
for (int i = rev_start + 1; i < rev.Length; ++i)
{
if (rev[i] == ']')
{
c++;
}
if (rev[i] == '[')
{
if (c == 0)
{
return str.Length - i - 1;
}
else
{
c--;
}
}
}
return -1;
}
public static void Main(string[] args)
{
int[] memory = new int[3000];
int address = 0;
string str = "+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+.";
for (int i = 0; i < str.Length; i++)
{
switch (str[i])
{
case '>':
address++;
break;
case '<':
address--;
break;
case '.':
Console.Write((char)memory[address]);
break;
case '+':
memory[address]++;
break;
case '-':
memory[address]--;
break;
case '[':
if (memory[address] == 0)
{
i = search1(str, i);
}
break;
case ']':
if (memory[address] != 0)
{
i = search2(str, i);
}
break;
}
}
}
}
}