もう今更感はありますが、C# で Brainf*ck のインタプリタを作ってみましたw
class Brainf_ck
{
int ptr;
char[] memory;
delegate void Action(string program, ref int index);
Dictionary<char, Action> actionDictionary;
public Brainf_ck()
{
memory = new char[65536];
actionDictionary = new Dictionary<char, Action>();
actionDictionary.Add('>', delegate { ++ptr; });
actionDictionary.Add('<', delegate { --ptr; });
actionDictionary.Add('+', delegate { ++memory[ptr]; });
actionDictionary.Add('-', delegate { --memory[ptr]; });
actionDictionary.Add(',', delegate { memory[ptr] = Console.ReadKey(true).KeyChar; });
actionDictionary.Add('.', delegate { Console.Write(memory[ptr]); });
actionDictionary.Add('[',
delegate(string program, ref int index)
{
if (memory[ptr] == 0)
{
int depth = 1;
while (depth != 0)
{
++index;
if (program[index] == '[') ++depth;
if (program[index] == ']') --depth;
}
}
}
);
actionDictionary.Add(']',
delegate(string program, ref int index)
{
int depth = -1;
while (depth != 0)
{
--index;
if (program[index] == '[') ++depth;
if (program[index] == ']') --depth;
}
--index;
}
);
}
public void Run(string program)
{
ptr = 0;
for (int i = 0; i < memory.Length; i++)
{
memory[i] = (char)0;
}
for (int index = 0; index < program.Length; index++)
{
if (actionDictionary.ContainsKey(program[index]))
{
actionDictionary[program[index]](program, ref index);
}
}
}
}
class Program
{
static void Main(string[] args)
{
string program = @"
>+++++++++[<++++++++>-]<.
>+++++++[<++++>-]<+.
+++++++.
.
+++.
[-]>++++++++[<++++>-]<.
>+++++++++++[<+++++>-]<.
>++++++++[<+++>-]<.
+++.
------.
--------.
[-]>++++++++[<++++>-]<+.
";
(new Brainf_ck()).Run(program);
}
}
これでいろんな計算が出来るんだから、チューリングマシンてすごいなぁ……。