-
-
Save it-is-wednesday/c60cc571db70b29a4d0aa47c2e74a9f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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