/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

  1. package com.ciriscr.desafios
  2. import scala.collection.mutable.ArrayBuffer
  3. /**
  4. * Created with IntelliJ IDEA.
  5. * User: londo
  6. * Date: 23/07/12
  7. * Time: 08:24 PM
  8. */
  9. //código fuente; https://bitbucket.org/londo/solveet-desafios
  10. trait BrainfuckInterpreter {
  11. private val mem = ArrayBuffer.fill[Int](30000)(0)
  12. private var dp = 0
  13. def interpretar(in: Array[Char]) {
  14. var i = 0
  15. println()
  16. while (in.size > i) {
  17. in(i) match {
  18. case '>' => dp += 1
  19. case '<' => dp -= 1
  20. case '+' => mem(dp) += 1
  21. case '-' => mem(dp) -= 1
  22. case '.' => println(mem(dp))
  23. // case ',' =>
  24. case '[' => i = despues(in)(']', i)
  25. case ']' => i = anterior(in)('[', i)
  26. case f @ _ => throw new UnsupportedOperationException(f + " no soportado")
  27. }
  28. i += 1
  29. }
  30. }
  31. def anterior(in: Array[Char])(c: Char, i: Int): Int = {
  32. if (dp == 0 || in(i) == c) i
  33. else anterior(in)(c, i-1)
  34. }
  35. def despues(in: Array[Char])(c: Char, i: Int): Int = {
  36. if (dp == 0 || in(i) == c) i
  37. else despues(in)(c, i+1)
  38. }
  39. }