/problemas/src/main/scala/com/ciriscr/desafios/BrainfuckInterpreter.scala
https://gitlab.com/eobandob/solveet · Scala · 47 lines · 31 code · 8 blank · 8 comment · 11 complexity · fad55445590b22d3ebeaa7209ff2f9ca MD5 · raw file
- package com.ciriscr.desafios
- import scala.collection.mutable.ArrayBuffer
- /**
- * Created with IntelliJ IDEA.
- * User: londo
- * Date: 23/07/12
- * Time: 08:24 PM
- */
- //código fuente; https://bitbucket.org/londo/solveet-desafios
- trait BrainfuckInterpreter {
- private val mem = ArrayBuffer.fill[Int](30000)(0)
- private var dp = 0
- def interpretar(in: Array[Char]) {
- var i = 0
- println()
- while (in.size > i) {
- in(i) match {
- case '>' => dp += 1
- case '<' => dp -= 1
- case '+' => mem(dp) += 1
- case '-' => mem(dp) -= 1
- case '.' => println(mem(dp))
- // case ',' =>
- case '[' => i = despues(in)(']', i)
- case ']' => i = anterior(in)('[', i)
- case f @ _ => throw new UnsupportedOperationException(f + " no soportado")
- }
- i += 1
- }
- }
- def anterior(in: Array[Char])(c: Char, i: Int): Int = {
- if (dp == 0 || in(i) == c) i
- else anterior(in)(c, i-1)
- }
- def despues(in: Array[Char])(c: Char, i: Int): Int = {
- if (dp == 0 || in(i) == c) i
- else despues(in)(c, i+1)
- }
- }