7 |
7 |
8 // loding a bf-file |
8 // loding a bf-file |
9 def load_bff(name: String) : String = |
9 def load_bff(name: String) : String = |
10 Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("") |
10 Try(Source.fromFile(name)("ISO-8859-1").mkString).getOrElse("") |
11 |
11 |
|
12 // "splicing" a BF program counting occurrences |
12 def splice(cs: List[Char], acc: List[(Char, Int)]) : List[(Char, Int)] = (cs, acc) match { |
13 def splice(cs: List[Char], acc: List[(Char, Int)]) : List[(Char, Int)] = (cs, acc) match { |
13 case (Nil, acc) => acc |
14 case (Nil, acc) => acc |
14 case (c :: cs, Nil) => splice(cs, List((c, 1))) |
15 case (c :: cs, Nil) => splice(cs, List((c, 1))) |
15 case (c :: cs, (d, n) :: acc) => |
16 case (c :: cs, (d, n) :: acc) => |
16 if (c == d) splice(cs, (c, n + 1) :: acc) |
17 if (c == d) splice(cs, (c, n + 1) :: acc) |
17 else splice(cs, (c, 1) :: (d, n) :: acc) |
18 else splice(cs, (c, 1) :: (d, n) :: acc) |
18 } |
19 } |
19 |
20 |
20 def spl(s: String) = splice(s.toList, Nil).reverse |
21 def spl(s: String) = splice(s.toList, Nil).reverse |
21 |
22 |
|
23 // generating "compound" c-instructions |
22 def instr2(c: Char, n: Int) : String = c match { |
24 def instr2(c: Char, n: Int) : String = c match { |
23 case '>' => "ptr += " + n.toString + ";" |
25 case '>' => "ptr += " + n.toString + ";" |
24 case '<' => "ptr -= " + n.toString + ";" |
26 case '<' => "ptr -= " + n.toString + ";" |
25 case '+' => "(*ptr) += " + n.toString + ";" |
27 case '+' => "(*ptr) += " + n.toString + ";" |
26 case '-' => "(*ptr) -= " + n.toString + ";" |
28 case '-' => "(*ptr) -= " + n.toString + ";" |
69 for (i <- 0 until n) code |
71 for (i <- 0 until n) code |
70 val end = System.nanoTime() |
72 val end = System.nanoTime() |
71 (end - start) / (n * 1.0e9) |
73 (end - start) / (n * 1.0e9) |
72 } |
74 } |
73 |
75 |
|
76 // mandelbrot program |
|
77 val b0 = load_bff("mandelbrot.bf") |
74 |
78 |
75 println(s"${time_needed(1, compile_run(load_bff("mandelbrot.bf")))} secs") |
79 println(s"${time_needed(1, compile_run(b0))} secs") |
76 |
80 |
77 |
81 |
78 |
82 |
79 // a benchmark program (counts down from 'Z' to 'A') |
83 // a benchmark program (counts down from 'Z' to 'A') |
80 val b1 = """>++[<+++++++++++++>-]<[[>+>+<<-]>[<+>-]++++++++ |
84 val b1 = """>++[<+++++++++++++>-]<[[>+>+<<-]>[<+>-]++++++++ |