Skip to content

Instantly share code, notes, and snippets.

@it-is-wednesday it-is-wednesday/tictactoe.kt Secret
Last active Aug 20, 2018

Embed
What would you like to do?
enum class Symbol(val text: String) { X("X"), O("O"), EMPTY("Tie") }
data class Slot(val x: Int, val y: Int, val symbol: Symbol)
fun main(args: Array<String>) {
val input = args.getOrNull(0)
if (input == null) {
println("No input!")
return
}
val result = input
.toCharArray()
.mapIndexed { i, c -> Slot(x = i % 3, y = i / 3, symbol = parseSymbol(c)) }
.groupBy(Slot::symbol)
.entries
.filter { it.key != Symbol.EMPTY }
.find { hasLinearSlope(it.value) }
?.key
?.text
println(result ?: "Tie")
}
fun parseSymbol(char: Char): Symbol = when (char) {
'X' -> Symbol.X
'O' -> Symbol.O
'#' -> Symbol.EMPTY
else -> throw IllegalArgumentException("Bad input fam")
}
fun hasLinearSlope(slots: List<Slot>): Boolean = slots
.combinationsOfThree()
.any { slope(it.first, it.second) == slope(it.second, it.third) }
fun <T> List<T>.combinationsOfThree(): List<Triple<T, T, T>> =
List(size = this.size) { i ->
List(size = this.size - i) { j ->
List(size = this.size - j) { h ->
Triple(this[i], this[i + j], this[j + h])
}
}
}.flatten().flatten().filter { it.first != it.second && it.second != it.third }
fun slope(slot1: Slot, slot2: Slot): Float =
(slot1.y - slot2.y).toFloat() / (slot1.x - slot2.x).toFloat()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.