Advertisement
KoMeDiAnT

Brainfuck Loop Commands

Mar 17th, 2017
1,951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace func.brainfuck
  6. {
  7.     public class BrainfuckLoopCommands
  8.     {
  9.         public static Dictionary<int, int> Bracket = new Dictionary<int, int>();
  10.         public static Dictionary<int, int> ClosingBracket = new Dictionary<int, int>();
  11.         public static Stack<int> Stack = new Stack<int>();
  12.  
  13.         public static void BodyLoop(IVirtualMachine vm)
  14.         {
  15.             for (int i = 0; i < vm.Instructions.Length; i++)
  16.             {
  17.                 var bracket = vm.Instructions[i];
  18.                 switch (bracket)
  19.                 {
  20.                     case '[':
  21.                         Stack.Push(i);
  22.                         break;
  23.                     case ']':
  24.                         ClosingBracket[i] = Stack.Peek();
  25.                         Bracket[Stack.Pop()] = i;
  26.                         break;
  27.                 }
  28.             }
  29.         }
  30.  
  31.         public static void RegisterTo(IVirtualMachine vm)
  32.         {
  33.             BodyLoop(vm);
  34.  
  35.             vm.RegisterCommand('[', machine =>
  36.             {
  37.                 if (machine.Memory[machine.MemoryPointer] == 0)
  38.                 {
  39.                     machine.InstructionPointer = Bracket[machine.InstructionPointer];
  40.                 }
  41.             });
  42.             vm.RegisterCommand(']', machine =>
  43.             {
  44.                 if (machine.Memory[machine.MemoryPointer] != 0)
  45.                 {
  46.                     machine.InstructionPointer = ClosingBracket[machine.InstructionPointer];
  47.                 }
  48.             });
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement