Advertisement
sci4me

BrainFuck

Aug 26th, 2015
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.82 KB | None | 0 0
  1. func runCode(program string) {
  2.     data := make([]byte, 100000)
  3.     ip := 0
  4.     dp := 0
  5.     ld := 0
  6.  
  7.     for ; ip < len(program); ip++ {
  8.         switch program[ip] {
  9.         case '+':  
  10.             data[dp]++
  11.         case '-':
  12.             data[dp]--
  13.         case '>':
  14.             dp++
  15.         case '<':
  16.             dp--
  17.         case '.':
  18.             fmt.Print(string(data[dp]))
  19.         case ',':
  20.             b := make([]byte, 1)
  21.             os.Stdin.Read(b)
  22.             data[dp] = b[0]
  23.         case '[':
  24.             if data[dp] == 0 {
  25.                 ip++
  26.  
  27.                 for ld > 0 || program[ip] != ']' {
  28.                     if program[ip] == '[' {
  29.                         ld++
  30.                     } else if program[ip] == ']' {
  31.                         ld--
  32.                     }
  33.                     ip++
  34.                 }
  35.             }
  36.         case ']':
  37.             if data[dp] != 0 {
  38.                 ip--
  39.                 for ld > 0 || program[ip] != '[' {
  40.                     if program[ip] == ']' {
  41.                         ld++
  42.                     } else if program[ip] == '[' {
  43.                         ld--
  44.                     }
  45.                     ip--
  46.                 }
  47.                 ip--
  48.             }
  49.         }
  50.     }
  51.  
  52.     fmt.Println()
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement