Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Brainf*ck interpreter
//Title of this code //Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { string code = ""; for (string line = Console.ReadLine(); line != "END"; line = Console.ReadLine()) { int comment = line.IndexOf('#'); if (comment != -1) code += line.Substring(0, comment); else code += line; } new BfInterpreter(code); } } public class BfInterpreter { List<byte> array = new List<byte>(new byte[512]); int dataPtr = 0; int instPtr = 0; Stack<int> loopStack = new Stack<int>(); string code; Dictionary<char, Action> instructionMap; public BfInterpreter(string inCode) { code = Regex.Replace(inCode, "\\s", ""); instructionMap = new Dictionary<char, Action> { { '+', Plus }, { '-', Minus }, { '>', MoveUp }, { '<', MoveDown }, { '.', Output }, { ',', Input }, { '[', StartLoop }, { ']', EndLoop }, }; for (instPtr = 0; instPtr < code.Length; instPtr++) { char cmd = code[instPtr]; try { instructionMap[cmd](); } catch (KeyNotFoundException e) { throw new Exception(string.Format("\nUnrecognized input: '{0}'", cmd)); } } Console.WriteLine("\n"); for (int i = 0; i < 40; i++) { Console.Write(array[i].ToString() + ","); } } void Plus() { array[dataPtr]++; } void Minus() { array[dataPtr]--; } void MoveUp() { dataPtr++; } void MoveDown() { dataPtr--; } void Output() { char output = (char)array[dataPtr]; if (char.IsControl(output)) Console.Write("[{0}]", array[dataPtr]); else Console.Write(output); } void Input() { array[dataPtr] = (byte)Console.Read(); } void StartLoop() { if (array[dataPtr] != 0) { loopStack.Push(instPtr); return; } int nests = 1; while (nests > 0) { if (instPtr == code.Length) { throw new Exception("No matching end brace"); } int nextBraceIndex = code.IndexOfAny("[]".ToCharArray(), ++instPtr); if (nextBraceIndex == -1) { throw new Exception("No matching end brace"); } nests += code[nextBraceIndex] == '[' ? 1 : -1; instPtr = nextBraceIndex; } } void EndLoop() { try { instPtr = loopStack.Pop() - 1; } catch (InvalidOperationException e) { throw new Exception("No matching start brace"); } } } }
run
|
edit
|
history
|
help
1
== and Equals Differeance in C#
page 2
ProWIN2
Carnival 1.0
2.1.1 Basic types: Lists and Linq - caveat
ArrayList list merge_collections
Main 5.4
IF... ELSE
example
Array Foreach with sum