Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created January 20, 2014 18:13
Show Gist options
  • Save fancellu/8525692 to your computer and use it in GitHub Desktop.
Save fancellu/8525692 to your computer and use it in GitHub Desktop.
Scala Sunspot Interview question I was given. Here's the word doc question https://app.box.com/s/1e8ukxjr25f2luj99t2f
main(1, 5, "5 3 1 2 0 4 1 1 3 2 2 3 2 4 3 0 2 3 3 2 1 0 2 4 3")
(3,3 score: 26)
main(3, 4, "2 3 2 1 4 4 2 0 3 4 1 1 2 3 4 4")
(1,2 score: 27)(1,1 score: 25)(2,2 score: 23)
main(2, 4, "4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4")
(1,1 score: 36)(2,1 score: 36)(1,2 score: 36)(2,2 score: 36)
object SunSpot {
def main(args: Array[String]): Unit = {
type Cube = Array[Array[Int]]
def sumCube(arr: Cube):Int = arr map (_.sum) sum
def getSampleCube(cube: Cube, y: Int, x: Int): Cube = cube.slice(y - 1, y + 2) map (_.slice(x - 1, x + 2))
def toCube(st: String, size: Int): Cube = st.split(" ").map(_.toInt).grouped(size).toArray
def getScoreCube(cube: Cube):Cube = {
Array.tabulate[Int](cube.length, cube.length) { (y, x) => sumCube(getSampleCube(cube, y, x)) }
}
def printTop(t: Int, size: Int, input: String) {
val scores: Cube = getScoreCube(toCube(input, size))
val topScores = (Array.concat(scores: _*) sorted).reverse take t
val xyScores = for (score <- topScores.distinct; y <- 0 until scores.length; x <- 0 until scores.length if scores(y)(x) == score)
yield (x, y, score)
xyScores.foreach { case (x, y, score) => print(s"($x,$y score: $score)") }
println
}
printTop(1, 5, "5 3 1 2 0 4 1 1 3 2 2 3 2 4 3 0 2 3 3 2 1 0 2 4 3")
printTop(3, 4, "2 3 2 1 4 4 2 0 3 4 1 1 2 3 4 4")
printTop(2, 4, "4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment