testing5/bf.scala
changeset 340 9eeab89d0671
parent 325 ca9c1cf929fa
equal deleted inserted replaced
339:16f437306f61 340:9eeab89d0671
     1 // Core Part about an Interpreter for 
     1 // Core Part about an Interpreter for 
     2 // the Brainf*** language
     2 // the Brainf***++ language
     3 //=========================================
     3 //==============================================
     4 
     4 
     5 object CW10a {
     5 object CW10a {  
     6 
     6 
       
     7 
       
     8 // representation of Bf memory 
     7 
     9 
     8 type Mem = Map[Int, Int]
    10 type Mem = Map[Int, Int]
     9 
    11 
    10 
       
    11 import io.Source
       
    12 import scala.util._
       
    13 
    12 
    14 // (1) Write a function that takes a file name as argument and
    13 // (1) Write a function that takes a file name as argument and
    15 // and requests the corresponding file from disk. It Returns the
    14 // and requests the corresponding file from disk. It Returns the
    16 // content of the file as a String. If the file does not exists,
    15 // content of the file as a String. If the file does not exists,
    17 // the function should Return the empty string.
    16 // the function should Return the empty string.
    18 
    17 
       
    18 import io.Source
       
    19 import scala.util._
       
    20 
    19 def load_bff(name: String) : String = 
    21 def load_bff(name: String) : String = 
    20   Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("")
    22   Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("")
    21 
    23 
    22 
    24 
    23 // (2) Complete the functions for safely reading  
    25 // (2) Complete the functions for safely reading  
    24 // and writing brainf*** memory. Safely read should
    26 // and writing brainf***++ memory. Safely read should
    25 // Return the value stored in the Map for a given memory
    27 // Return the value stored in the Map for a given memory
    26 // pointer, provided it exists; otherwise it Returns 0. The
    28 // pointer, provided it exists; otherwise it Returns 0. The
    27 // writing function generates a new Map with the
    29 // writing function generates a new Map with the
    28 // same data, except at the given memory pointer the
    30 // same data, except at the given memory pointer the
    29 // value v is stored.
    31 // value v is stored.
    35 def write(mem: Mem, mp: Int, v: Int) : Mem =
    37 def write(mem: Mem, mp: Int, v: Int) : Mem =
    36   mem.updated(mp, v)
    38   mem.updated(mp, v)
    37 
    39 
    38 
    40 
    39 // (3) Implement the two jumping instructions in the 
    41 // (3) Implement the two jumping instructions in the 
    40 // brainf*** language. In jumpRight, given a program and 
    42 // brainf***++ language. In jumpRight, given a program and 
    41 // a program counter move the program counter to the right 
    43 // a program counter move the program counter to the right 
    42 // until after the *matching* ]-command. Similarly, 
    44 // until after the *matching* ]-command. Similarly, 
    43 // jumpLeft implements the move to the left to just after
    45 // jumpLeft implements the move to the left to just after
    44 // the *matching* [-command.
    46 // the *matching* [-command.
    45 
    47 
    62     case (_, l) => jumpLeft(prog, pc - 1, l)
    64     case (_, l) => jumpLeft(prog, pc - 1, l)
    63   }
    65   }
    64 }
    66 }
    65 
    67 
    66 // test cases
    68 // test cases
    67 //jumpRight("""--[..+>--],>,++""", 3, 0)         // => 10
    69 //jumpRight("""--[..+>--].>.++""", 3, 0)         // => 10
    68 //jumpLeft("""--[..+>--],>,++""", 8, 0)          // => 3
    70 //jumpLeft("""--[..+>--].>.++""", 8, 0)          // => 3
    69 //jumpRight("""--[..[+>]--],>,++""", 3, 0)       // => 12
    71 //jumpRight("""--[..[+>]--].>.++""", 3, 0)       // => 12
    70 //jumpRight("""--[..[[-]+>[.]]--],>,++""", 3, 0) // => 18
    72 //jumpRight("""--[..[[-]+>[.]]--].>.++""", 3, 0) // => 18
    71 //jumpRight("""--[..[[-]+>[.]]--,>,++""", 3, 0)  // => 22 (outside)
    73 //jumpRight("""--[..[[-]+>[.]]--.>.++""", 3, 0)  // => 22 (outside)
    72 //jumpLeft("""[******]***""", 7, 0)              // => -1 (outside)
    74 //jumpLeft("""[******]***""", 7, 0)              // => -1 (outside)
    73 
    75 
    74 // (4) Complete the compute function that interprets (runs) a brainf***
    76 // (4) Complete the compute function that interprets (runs) a brainf***++
    75 // program: the arguments are a program (represented as a string), a program 
    77 // program: the arguments are a program (represented as a string), a program 
    76 // counter, a memory counter and a brainf*** memory. It Returns the
    78 // counter, a memory counter and a brainf***++ memory. It Returns the
    77 // memory at the stage when the execution of the brainf*** program
    79 // memory at the stage when the execution of the brainf***++ program
    78 // finishes. The interpretation finishes once the program counter
    80 // finishes. The interpretation finishes once the program counter
    79 // pc is pointing to something outside the program string.
    81 // pc is pointing to something outside the program string.
    80 // If the pc points to a character inside the program, the pc, 
    82 // If the pc points to a character inside the program, the pc, 
    81 // memory pointer and memory need to be updated according to 
    83 // memory pointer and memory need to be updated according to 
    82 // rules of the brainf*** language. Then, recursively, the compute 
    84 // rules of the brainf***++ language. Then, recursively, the compute 
    83 // function continues with the command at the new program
    85 // function continues with the command at the new program
    84 // counter. 
    86 // counter. 
       
    87 //
    85 // Implement the run function that calls compute with the program
    88 // Implement the run function that calls compute with the program
    86 // counter and memory counter set to 0.
    89 // counter and memory counter set to 0.
    87 
    90 
    88 def compute(prog: String, pc: Int, mp: Int, mem: Mem) : Mem = {
    91 def compute(prog: String, pc: Int, mp: Int, mem: Mem) : Mem = {
    89   if (0 <= pc && pc < prog.length) { 
    92   if (0 <= pc && pc < prog.length) { 
    91       case '>' => (pc + 1, mp + 1, mem)
    94       case '>' => (pc + 1, mp + 1, mem)
    92       case '<' => (pc + 1, mp - 1, mem)
    95       case '<' => (pc + 1, mp - 1, mem)
    93       case '+' => (pc + 1, mp, write(mem, mp, sread(mem, mp) + 1))
    96       case '+' => (pc + 1, mp, write(mem, mp, sread(mem, mp) + 1))
    94       case '-' => (pc + 1, mp, write(mem, mp, sread(mem, mp) - 1))
    97       case '-' => (pc + 1, mp, write(mem, mp, sread(mem, mp) - 1))
    95       case '.' => { print(sread(mem, mp).toChar); (pc + 1, mp, mem) }
    98       case '.' => { print(sread(mem, mp).toChar); (pc + 1, mp, mem) }
    96       case ',' => (pc + 1, mp, write(mem, mp, scala.io.StdIn.readByte()))
    99       //case ',' => (pc + 1, mp, write(mem, mp, Console.in.read().toByte))
       
   100       //case ',' => (pc + 1, mp, write(mem, mp, scala.io.StdIn.readByte()))
    97       case '['  => 
   101       case '['  => 
    98 	if (sread(mem, mp) == 0) (jumpRight(prog, pc + 1, 0), mp, mem) else (pc + 1, mp, mem) 
   102 	      if (sread(mem, mp) == 0) (jumpRight(prog, pc + 1, 0), mp, mem) else (pc + 1, mp, mem) 
    99       case ']'  => 
   103       case ']'  => 
   100 	if (sread(mem, mp) != 0) (jumpLeft(prog, pc - 1, 0), mp, mem) else (pc + 1, mp, mem) 
   104 	      if (sread(mem, mp) != 0) (jumpLeft(prog, pc - 1, 0), mp, mem) else (pc + 1, mp, mem) 
       
   105  
       
   106       // new commands
       
   107       case '@' => (pc + 1, mp, write(mem, sread(mem, mp), sread(mem, mp - 1)))
       
   108       case '*' => (pc + 1, mp, write(mem, mp, sread(mem, mp) * sread(mem, mp -1)))
       
   109       case '#' => { println(s"${sread(mem, mp)}"); (pc + 1, mp, mem) }
       
   110       
   101       case _ => (pc + 1, mp, mem)
   111       case _ => (pc + 1, mp, mem)
   102     }		     
   112     }		     
   103     compute(prog, new_pc, new_mp, new_mem)	
   113     compute(prog, new_pc, new_mp, new_mem)	
   104   }
   114   }
   105   else mem
   115   else mem
   106 }
   116 }
   107 
   117 
   108 def run(prog: String, m: Mem = Map()) = compute(prog, 0, 0, m)
   118 def run(prog: String, m: Mem = Map()) = compute(prog, 0, 0, m)
   109 
   119 
   110 
   120 
   111 /*
   121 
   112 
   122 
   113 // some sample bf-programs collected from the Internet
   123 
   114 //=====================================================
   124 // some sample bf/bf++-programs collected from the Internet
   115 
   125 //==========================================================
   116 
   126 
   117 // first some contrived (small) programs
   127 
       
   128 // some contrived (small) programs
       
   129 //---------------------------------
   118 
   130 
   119 // clears the 0-cell
   131 // clears the 0-cell
   120 run("[-]", Map(0 -> 100))    // Map will be 0 -> 0
   132 //run("[-]", Map(0 -> 100))    // Map will be 0 -> 0
   121 
   133 
   122 // copies content of the 0-cell to 1-cell
   134 // moves content of the 0-cell to 1-cell
   123 run("[->+<]", Map(0 -> 10))  // Map will be 0 -> 0, 1 -> 10
   135 //run("[->+<]", Map(0 -> 10))  // Map will be 0 -> 0, 1 -> 10
   124 
   136 
   125 
   137 
   126 // copies content of the 0-cell to 2-cell and 4-cell
   138 // copies content of the 0-cell to 2-cell and 4-cell
   127 run("[>>+>>+<<<<-]", Map(0 -> 42))
   139 //run("[>>+>>+<<<<-]", Map(0 -> 42))    // Map(0 -> 0, 2 -> 42, 4 -> 42)
   128 
   140 
   129 
   141 
   130 // prints out numbers 0 to 9
   142 // prints out numbers 0 to 9
   131 run("""+++++[->++++++++++<]>--<+++[->>++++++++++<<]>>++<<----------[+>.>.<+<]""")
   143 //run("""+++++[->++++++++++<]>--<+++[->>++++++++++<<]>>++<<----------[+>.>.<+<]""")
       
   144 
       
   145 // bf++ program calculating the cube-function, 10 * 10 * 10 = 1000
       
   146 //run("""++++++++++#>+***#""")           // Map(0 -> 10, 1 -> 1000)
       
   147 
       
   148 
       
   149 // bf++ program copies 3 from 0-cell to to cells 1, 4, 5, 6 and 7
       
   150 // (note that because of how the program wprks cell 1 will contain 7) 
       
   151 //run("""+++>+@+@+@+@+@""")   // Map(0 -> 3, 1 -> 7, 4 -> 3, 5 -> 3, 6 -> 3, 7 -> 3)
       
   152 
   132 
   153 
   133 
   154 
   134 // some more "useful" programs
   155 // some more "useful" programs
       
   156 //-----------------------------
   135 
   157 
   136 // hello world program 1
   158 // hello world program 1
   137 run("""++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++
   159 //run("""++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++
   138        ..+++.>>.<-.<.+++.------.--------.>>+.>++.""")
   160 //       ..+++.>>.<-.<.+++.------.--------.>>+.>++.""")
   139 
   161 
   140 // hello world program 2
   162 // hello world program 2
   141 run("""++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>+
   163 //run("""++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>+
   142       +.<<+++++++++++++++.>.+++.------.--------.>+.>.""")
   164 //       +.<<+++++++++++++++.>.+++.------.--------.>+.>.""")
   143 
   165 
   144 
   166 // hello world program 3
       
   167 //run("""+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..
       
   168 //       +++.>-.------------.<++++++++.--------.+++.------.--------.>+.""")
       
   169 
       
   170  
   145 // draws the Sierpinski triangle
   171 // draws the Sierpinski triangle
   146 run("""++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[
   172 //run(load_bff("sierpinski.bf"))
   147       ->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<
       
   148       ]>.>+[>>]>+]""")
       
   149 
       
   150 run(load_bff("sierpinski.bf"))
       
   151 
   173 
   152 
   174 
   153 //fibonacci numbers below 100
   175 //fibonacci numbers below 100
   154 run("""+++++++++++
   176 //run("""+++++++++++
   155       >+>>>>++++++++++++++++++++++++++++++++++++++++++++
   177 //      >+>>>>++++++++++++++++++++++++++++++++++++++++++++
   156       >++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>
   178 //      >++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>
   157       +<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-
   179 //      +<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-
   158       <-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<
   180 //      <-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<
   159       -]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]
   181 //      -]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]
   160       >[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++
   182 //      >[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++
   161       +++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++
   183 //      +++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++
   162       ++++++++++++++++++++++++++++++++++++++++++++.[-]<<
   184 //      ++++++++++++++++++++++++++++++++++++++++++++.[-]<<
   163       <<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<
   185 //      <<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<
   164       [-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]""")
   186 //      [-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]""")
   165 
       
   166 
   187 
   167 //outputs the square numbers up to 10000
   188 //outputs the square numbers up to 10000
   168 run("""++++[>+++++<-]>[<+++++>-]+<+[
   189 //run("""++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+
   169     >[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+
   190 //       >>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]
   170     >>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]
   191 //       <<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]""")
   171     <<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]""")
   192 
   172 
   193 
   173 //collatz numbers (needs a number to be typed in)
   194 // calculates 2 to the power of 6 
   174 run(""">,[[----------[
   195 //(example from a C-to-BF compiler at https://github.com/elikaski/BF-it)
   175       >>>[>>>>]+[[-]+<[->>>>++>>>>+[>>>>]++[->+<<<<<]]<<<]
   196 //run(""">>[-]>[-]++>[-]++++++><<<>>>>[-]+><>[-]<<[-]>[>+<<+>-]>[<+>-]
   176       ++++++[>------<-]>--[>>[->>>>]+>+[<<<<]>-],<]>]>>>++>+>>[
   197 //       <><[-]>[-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]><<>>[-]>[-]<<<[>>[-]
   177       <<[>>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<<]]<[>+<-]>]
   198 //       <[>+>+<<-]>[<+>-]+>[[-]<-<->>]<<<-]>>[<<+>>-]<<[[-]>[-]<<[>+>
   178       >[>[>>>>]+[[-]<[+[->>>>]>+<]>[<+>[<<<<]]+<<<<]>>>[->>>>]+>+[<<<<]]
   199 //       +<<-]>>[<<+>>-][-]>[-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]
   179       >[[>+>>[<<<<+>>>>-]>]<<<<[-]>[-<<<<]]>>>>>>>
   200 //       <<>>[-]>[-]<<<[>>>+<<<-]>>>[<<[<+>>+<-]>[<+>-]>-]<<<>[-]<<[-]
   180       ]>>+[[-]++++++>>>>]<<<<[[<++++++++>-]<.[-]<[-]<[-]<]<,]""")
   201 //       >[>+<<+>-]>[<+>-]<><[-]>[-]<<<[>>+>+<<<-]>>>-[<<<+>>>-]<[-]>[-]
   181 
   202 //       <<<[>>+>+<<<-]>>>[<<<+>>>-][-]><<>>[-]>[-]<<<[>>[-]<[>+>+<<-]>
   182 
   203 //       [<+>-]+>[[-]<-<->>]<<<-]>>[<<+>>-]<<][-]>[-]<<[>+>+<<-]>>[<<+>
   183 // infinite collatz (never stops)
   204 //       >-]<<<<<[-]>>>>[<<<<+>>>>-]<<<<><>[-]<<[-]>[>+<<+>-]>[<+>-]<>
   184 run(""">>+>+<[[->>[>>]>>>[>>]+[<<]<<<[<<]>[>[>>]>>+>[>>]<+<[<<]<<<[<
   205 //       <[-]>[-]>[-]<<<[>>+>+<<<-]>>>[<<<+>>>-]<<>>[-]>[-]>[-]>[-]>[-]>
   185       <]>-]>[>>]>>[<<<<[<<]>+>[>>]>>-]<<<<[<<]+>>]<<[+++++[>+++++++
   206 //       [-]>[-]>[-]>[-]>[-]<<<<<<<<<<>>++++++++++<<[->+>-[>+>>]>[+[-<+
   186       +<-]>.<++++++[>--------<-]+<<]>>[>>]+[>>>>[<<+>+>-]<-[>+<-]+<
   207 //       >]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<
   187       [<<->>-[<<+>>[-]]]>>>[<<<+<<+>>>>>-]<<<[>>>+<<<-]<<[[-]>+>>->
   208 //       ]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++
   188       [<+<[<<+>>-]<[>+<-]<[>+<-]>>>>-]<[>+<-]+<[->[>>]<<[->[<+++>-[
   209 //       ++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<<><<<""")
   189       <+++>-[<+++>-[<[-]++>>[-]+>+<<-[<+++>-[<+++>-[<[-]+>>>+<<-[<+
       
   190       ++>-[<+++>-]]]]]]]]]<[>+<-]+<<]>>>+<[->[<+>-[<+>-[<+>-[<+>-[<
       
   191       +>-[<+>-[<+>-[<+>-[<+>-[<[-]>>[-]+>+<<-[<+>-]]]]]]]]]]]<[>+<-
       
   192       ]+>>]<<[<<]>]<[->>[->+>]<[-[<+>-[<->>+<-[<+>-[<->>+<-[<+>-[<-
       
   193       >>+<-[<+>-[<->>+<-[<+>-[<->>+<-[<+>-[<->>+<-[<+>-[<->>+<-[<+>
       
   194       -[<->>+<-[<+>-[<->>+<-[<+>-]]]]]]]]]]]]]]]]]]]>[<+>-]<+<[<+++
       
   195       +++++++>-]<]>>[<+>->>]<<[>+>+<<-]>[<+>-]+>[<->[-]]<[-<<-]<<[<
       
   196       <]]++++++[>+++++++<-]>++.------------.[-]>[>>]<<[+++++[>+++++
       
   197       +++<-]>.<++++++[>--------<-]+<<]+<]>[<+>-]<]>>>[>>]<<[>[-]<-<
       
   198       <]++++++++++.[-]<<<[<<]>>>+<[->[<+>-[<+>-[<+>-[<+>-[<+>-[<+>-
       
   199       [<+>-[<+>-[<+>-[<[-]>>[-]+>+<<-]]]]]]]]]]<[>+<-]+>>]<<[<<]>>]""")
       
   200 
   210 
   201 
   211 
   202 
   212 
   203 // a Mandelbrot set generator in brainf*** written by Erik Bosman
   213 // a Mandelbrot set generator in brainf*** written by Erik Bosman
   204 // (http://esoteric.sange.fi/brainfuck/utils/mandelbrot/)
   214 // (http://esoteric.sange.fi/brainfuck/utils/mandelbrot/)
   205 
   215 //
   206 run(load_bff("mandelbrot.bf"))
   216 //run(load_bff("mandelbrot.bf"))
   207 
   217 
   208 
   218 
   209 // a benchmark program (counts down from 'Z' to 'A')
   219 // a benchmark program (counts down from 'Z' to 'A')
   210 val b1 = """>++[<+++++++++++++>-]<[[>+>+<<-]>[<+>-]++++++++
   220 //
   211             [>++++++++<-]>.[-]<<>++++++++++[>++++++++++[>++
   221 //run(load_bff("benchmark.bf"))
   212             ++++++++[>++++++++++[>++++++++++[>++++++++++[>+
   222 
   213             +++++++++[-]<-]<-]<-]<-]<-]<-]<-]++++++++++."""
   223 // calculates the Collatz series for numbers from 1 to 30
   214 
   224 //
   215 
   225 //run(load_bff("collatz.bf"))
   216 def time_needed[T](n: Int, code: => T) = {
   226 
   217   val start = System.nanoTime()
   227 }
   218   for (i <- 0 until n) code
       
   219   val end = System.nanoTime()
       
   220   (end - start)/(n * 1.0e9)
       
   221 }
       
   222 
       
   223 
       
   224 */
       
   225 
       
   226 }