From e72f71c1bf78b8c89be14add9e4407593315e47c Mon Sep 17 00:00:00 2001 From: Hubert Van De Walle Date: Thu, 24 Dec 2020 16:11:12 +0100 Subject: [PATCH] Use custom class for faster hashcode --- days/src/main/kotlin/Day24.kt | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/days/src/main/kotlin/Day24.kt b/days/src/main/kotlin/Day24.kt index e90aa48..fa3d294 100644 --- a/days/src/main/kotlin/Day24.kt +++ b/days/src/main/kotlin/Day24.kt @@ -11,6 +11,10 @@ import org.eclipse.collections.api.factory.Bags @Day(24) class Day24(@Lines val input: Input>) { + private data class HexPoint(val x: Int, val y: Int, val z: Int) { + fun translate(other: HexPoint) = HexPoint(this.x + other.x, this.y + other.y, this.z + other.z) + } + private enum class Direction(vararg coordinates: Int) { E(1, -1, 0), SE(0, -1, 1), @@ -19,7 +23,7 @@ class Day24(@Lines val input: Input>) { NW(0, 1, -1), NE(1, 0, -1); - val coordinates = coordinates + val coordinates = HexPoint(coordinates[0], coordinates[1], coordinates[2]) } private fun parseTile(line: String) = "e|se|sw|w|nw|ne".toRegex() @@ -29,30 +33,18 @@ class Day24(@Lines val input: Input>) { .toList() private val tiles = input.value.map { parseTile(it) }.map { - it.map { it.coordinates } - .reduce { acc, ints -> intArrayOf(acc[0] + ints[0], acc[1] + ints[1], acc[2] + ints[2]) } - .toList() + it.map { it.coordinates }.reduce { acc, ints -> acc.translate(ints) } } fun part1() = Bags.immutable.ofAll(tiles).selectBlacks().size() - private fun Bag>.selectBlacks() = selectByOccurrences { it % 2 == 1 } + private fun Bag.selectBlacks() = selectByOccurrences { it % 2 == 1 } - private fun List.adjacents(): List> { - val (x, y, z) = this - return listOf( - listOf(x + 1, y - 1, z), - listOf(x, y - 1, z + 1), - listOf(x - 1, y, z + 1), - listOf(x - 1, y + 1, z), - listOf(x, y + 1, z - 1), - listOf(x + 1, y, z - 1), - ) - } + private fun HexPoint.adjacents() = Direction.values().map { this.translate(it.coordinates) } // black -> odd // white -> even || not in bag -> !in black - private fun day(bag: MutableBag>) { + private fun day(bag: MutableBag) { val blacks = bag.selectBlacks().toSet() val all = (bag + bag.flatMap { it.adjacents() }).toSet()