Skip to content

Commit 2e8f041

Browse files
committed
Added day08 part 2
1 parent 867f56b commit 2e8f041

File tree

2 files changed

+29
-16
lines changed

2 files changed

+29
-16
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ plugins {
44

55
// project meta data
66
group 'de.havox_design.aoc2023'
7-
version '0.7.4'
7+
version '0.7.5'
88

99
// Switch to gradle "all" distribution.
1010
wrapper {

day08/src/main/kotlin/de/havox_design/aoc2023/day08/Day08.kt

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Day08(private var filename: String) {
2222
var currentNode = NODES.first { node -> node.name == startNodeName }
2323
var instructionIndex = 0
2424

25-
while(currentNode.name != endNodeName) {
25+
while (currentNode.name != endNodeName) {
2626
val currentInstruction = INSTRUCTIONS[instructionIndex]
2727
instructionIndex++
2828
instructionIndex %= INSTRUCTIONS.size
@@ -37,26 +37,39 @@ class Day08(private var filename: String) {
3737
convertInput()
3838
val startNodeSuffix = "A"
3939
val endNodeSuffix = "Z"
40+
val startNodes = NODES.filter { node -> node.name.endsWith(startNodeSuffix) }
4041

41-
var steps = 0L
42-
var currentNodes = NODES.filter { node -> node.name.endsWith(startNodeSuffix) }
43-
val endNodes = NODES.filter { node -> node.name.endsWith(endNodeSuffix) }
44-
var instructionIndex = 0
42+
return startNodes
43+
.map { node -> findLoop(node, endNodeSuffix) }
44+
.fold(1L) { acc, i ->
45+
computeLeastCommonMultiple(acc, i.toLong())
46+
}
47+
}
4548

46-
while(!endNodes.containsAll(currentNodes)) {
47-
val currentInstruction = INSTRUCTIONS[instructionIndex]
48-
instructionIndex++
49-
instructionIndex %= INSTRUCTIONS.size
50-
currentNodes = currentNodes
51-
.parallelStream()
52-
.map{node -> node.getNode(currentInstruction)}
53-
.toList()
49+
private fun findLoop(start: Node, endNodeSuffix: String): Int {
50+
var index = 0
51+
var current = start
52+
var steps = 0
53+
54+
do {
55+
current = current.getNode(INSTRUCTIONS[index])
56+
index = (index + 1) % INSTRUCTIONS.size
5457
steps++
55-
}
58+
} while (!current.name.endsWith(endNodeSuffix))
5659

5760
return steps
5861
}
5962

63+
private fun computeLeastCommonMultiple(a: Long, b: Long): Long =
64+
a * b / computeGreatestCommonDivisor(a, b)
65+
66+
private fun computeGreatestCommonDivisor(a: Long, b: Long): Long =
67+
if (b == 0L) {
68+
a
69+
} else {
70+
computeGreatestCommonDivisor(b, a % b)
71+
}
72+
6073
private fun convertInput() {
6174
val input = getResourceAsText(filename)
6275

@@ -89,7 +102,7 @@ class Day08(private var filename: String) {
89102
NODES.add(Node(nodeName, null, null))
90103
}
91104

92-
for(entry in nodeInput) {
105+
for (entry in nodeInput) {
93106
val nodeName = entry.first
94107
val leftName = entry.second
95108
val rightName = entry.third

0 commit comments

Comments
 (0)