Skip to content

Instantly share code, notes, and snippets.

@kirked
Last active August 29, 2015 14:24
Show Gist options
  • Save kirked/2e1b4194a610ddcb4b70 to your computer and use it in GitHub Desktop.
Save kirked/2e1b4194a610ddcb4b70 to your computer and use it in GitHub Desktop.
Straightforward implementation of CodingGame ASCII art problem in Scala
object Solution extends App {
def readLetters(width: Int, height: Int): Array[Array[String]] = {
val chars = for (i <- 0 until height) yield readLine.grouped(width).toArray
chars.toArray
}
def letterIndex(c: Char): Int = if (c < 'A' || c > 'Z') 26 else c - 'A'
val l = readInt
val h = readInt
val t = readLine
// By (line)(char-index)
val letters = readLetters(l, h)
val message = for (line <- 0 until h) yield t.foldLeft("") { (prefix, letter) =>
prefix + letters(line)(letterIndex(letter.toUpper))
}
message foreach(line => println(line.mkString))
}
@kirked
Copy link
Author

kirked commented Jul 14, 2015

One thing that I would change for production code would be to avoid building up a string in this manner, and instead build up letter chunks. Doing it this way made it a simple foldLeft and there was no extra work to keep track where the newlines go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment