When you know deep-down that a Brainfuck interpreter should only ever be written in C, but you’re not quite ready to leave the comfort of C#. So in a spirit of minimalism you find yourself writing C# in a C style just for the hell of it.
public static void Execute(string program, Stream? input, Stream? output)
{
int ip = 0;
int dp = 0;
var data = new byte[30000];
while(true)
{
if (ip >= program.Length)
break;
switch(program[ip])
{
case '>':
dp++;
break;
case '<':
dp--;
break;
case '+':
data[dp]++;
break;
case '-':
data[dp]--;
break;
case '.':
output?.Write(data, dp, 1);
break;
case ',':
input?.Read(data, dp, 1);
break;
case '[':
if (data[dp] == 0)
ip = JumpTo(']', +1, program, ip);
break;
case ']':
if (data[dp] != 0)
ip = JumpTo('[', -1, program, ip);
break;
}
ip++;
}
}
private static int JumpTo(char match, int incr, string program, int ip)
{
while (true)
{
ip += incr;
if ( (match == ']' && program[ip] == '[') ||
(match == '[' && program[ip] == ']') )
ip = JumpTo(match, incr, ip, program);
else if (program[ip] == match)
return ip;
}
}
This made me wonder if the style of a language affects the style of its implementation. Not sure.
(For any impressionable children reading this: don’t do it this way. Use descriptive variable names and comments and put braces around your if/else clauses.)
(And for any hiring managers reading this: its deliberate, I promise.)