From 7d5c2834c2e1ca0f2d620d6c5eabcb4d8594a92b Mon Sep 17 00:00:00 2001 From: dnutiu Date: Sun, 3 Dec 2023 17:22:48 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=84Advent=20of=20Code=20-=20Day=203=20?= =?UTF-8?q?=E2=9C=A8=20part=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AdventOfCode2023/day3/GearRatios.kt | 43 ++++++++++++++++++- src/main/kotlin/Main.kt | 4 +- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/AdventOfCode2023/day3/GearRatios.kt b/src/main/kotlin/AdventOfCode2023/day3/GearRatios.kt index 76ae571..fd412af 100644 --- a/src/main/kotlin/AdventOfCode2023/day3/GearRatios.kt +++ b/src/main/kotlin/AdventOfCode2023/day3/GearRatios.kt @@ -96,7 +96,46 @@ class GearRatios : Puzzle { } override fun partTwo() { - // For each gear *, do a box search and multiply numbers to find gear ratio and then sum. - TODO("Not yet implemented") + val inputData = this.readInputFromFile("3") + val foundEngineParts: List = scanForEnginePats(inputData) + var gears: MutableList> = mutableListOf() + + inputData.forEachIndexed { row, rowElement -> + rowElement.forEachIndexed { col, colElement -> + if (colElement == '*') { + val enginePartsForGear: MutableSet = mutableSetOf() + val movesOfXY = listOf( + Pair(col-1, row), // left + Pair(col-1, row-1), // let top + Pair(col, row-1),// top + Pair(col+1, row-1), // right top + Pair(col+1, row), // right + Pair(col+1, row+1), // right bottom + Pair(col, row+1), // bottom + Pair(col-1, row+1) // left bottom + ) + movesOfXY.forEach movesForeach@ { + if ((it.second >= 0 && it.second < inputData.size) && (it.first >= 0 && it.first < inputData[it.second].length)) { + val symbol = inputData[it.second][it.first] + if (symbol.isDigit()) { + // search engine part + foundEngineParts.forEach {part -> + if (part.row == it.second && (it.first >= part.startIndex && it.first <= part.endIndex)) { + enginePartsForGear.add(part) + } + } + } + } + } + gears.add(enginePartsForGear) + } + } + } + + gears.filter { it.size == 2 }.map { + it.map { it.number }.reduce { acc, i -> acc * i } + }.sum().let { + println("The gear ratio is $it") + } } } \ No newline at end of file diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt index dcd0fc9..78696f3 100644 --- a/src/main/kotlin/Main.kt +++ b/src/main/kotlin/Main.kt @@ -2,6 +2,6 @@ import AdventOfCode2023.day3.GearRatios fun main(args: Array) { val t = GearRatios() - t.partOne() -// t.partTwo() + // t.partOne() + t.partTwo() } \ No newline at end of file