Skip to content

Instantly share code, notes, and snippets.

@thecoshman
Last active June 22, 2018 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thecoshman/4b6ec78811d4a28066a35c7ab61de5f1 to your computer and use it in GitHub Desktop.
Save thecoshman/4b6ec78811d4a28066a35c7ab61de5f1 to your computer and use it in GitHub Desktop.
My solution to a little Kotlin challange: https://gist.github.com/jjst/f90775efe7da80c749a140b125d6e48e
class GameState constructor (val width:Int, val height:Int, turnOnLights:List<Pair<Int, Int>>){
var lights = BooleanArray(width * height)
init {
for(light in turnOnLights){
toggle(light.first, light.second)
}
}
override fun toString(): String{
return lights.map{if(it) "x " else ". "}
.chunked(width)
.map{it + "\n"}
.flatten()
.fold("", { total, next -> total + next })
}
fun lightsOn() = lights.count{it == true}
fun press(coord: Pair<Int,Int>){
val (x, y) = coord
toggle(x, y)
toggle(x + 1, y)
toggle(x - 1, y)
toggle(x, y + 1)
toggle(x, y - 1)
}
private fun toggle(x:Int, y:Int){
if(x < 0 || y < 0 || x >= width || y >= height) {
return
}
lights[index(x, y)] = !lights[index(x, y)]
}
private fun index(x:Int, y:Int) = y * width + x
}
fun main(args: Array<String>) {
var game = GameState(5, 5, startingLights)
for(move in moves) {
game.press(move)
}
print(game)
println(game.lightsOn())
}
val startingLights = listOf(
Pair(1, 0),
Pair(3, 0),
Pair(1, 1),
Pair(2, 1),
Pair(3, 1),
Pair(4, 1),
Pair(0, 2),
Pair(1, 2),
Pair(3, 2),
Pair(4, 2),
Pair(0, 3),
Pair(1, 3),
Pair(2, 3),
Pair(3, 3),
Pair(4, 3),
Pair(0, 4),
Pair(1, 4),
Pair(2, 4),
Pair(3, 4),
Pair(4, 4))
val moves = listOf(
Pair(3, 2),
Pair(2, 4),
Pair(3, 3),
Pair(0, 3),
Pair(1, 2),
Pair(3, 1),
Pair(1, 4),
Pair(4, 0),
Pair(1, 4),
Pair(0, 1),
Pair(0, 1),
Pair(0, 2),
Pair(0, 2),
Pair(3, 1),
Pair(0, 4),
Pair(2, 2),
Pair(1, 3),
Pair(3, 1),
Pair(2, 2),
Pair(1, 1),
Pair(0, 0),
Pair(4, 3),
Pair(4, 4),
Pair(2, 3),
Pair(4, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment