Skip to content

Commit

Permalink
Day 22: Monkey Market (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
andilau authored Dec 22, 2024
1 parent d1796e8 commit 4d8b529
Show file tree
Hide file tree
Showing 5 changed files with 1,896 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Advent of Code is an Advent calendar of small programming puzzles by [Eric Wastl
- Day 12: [Garden Groups](https://adventofcode.com/2024/day/12) -- [Day12.kt](https://github.com/andilau/advent-of-code-2024/blob/main/src/main/kotlin/days/Day12.kt)
- Day 14: [Restroom Redoubt](https://adventofcode.com/2024/day/14) -- [Day14.kt](https://github.com/andilau/advent-of-code-2024/blob/main/src/main/kotlin/days/Day14.kt)
- Day 18: [RAM Run](https://adventofcode.com/2024/day/18) -- [Day18.kt](https://github.com/andilau/advent-of-code-2024/blob/main/src/main/kotlin/days/Day18.kt)
- Day 22: [Monkey Market](https://adventofcode.com/2024/day/22) -- [Day22.kt](https://github.com/andilau/advent-of-code-2024/blob/main/src/main/kotlin/days/Day22.kt)

### Features

Expand Down
54 changes: 54 additions & 0 deletions src/main/kotlin/days/Day22.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package days

@AdventOfCodePuzzle(
name = "Monkey Market",
url = "https://adventofcode.com/2024/day/22",
date = Date(day = 22, year = 2024)
)
class Day22(val input: List<String>) : Puzzle {
val secrets = input.map { it.toInt() }

override fun partOne(): Long {
return secrets.sumOf { secret ->
generateSequence(secret) { it.next() }
.take(2001)
.last().toLong()
}
}

override fun partTwo(): Int {
val seqPriceSums = mutableMapOf<List<Int>, Int>()
secrets.forEach { secret ->
println("secret = ${secret}")
val prices: List<Int> = generateSequence(secret) { it.next() }
.take(2001)
.map { it.mod(10) }
.toList()
val sequences = prices
.zipWithNext { a, b -> b - a }
.windowed(4)
.toList()
val zip = prices.drop(4).zip(sequences)
val seen = mutableSetOf<List<Int>>()
for ((price, seq) in zip) {
if (seq in seen) continue
seen += seq
seqPriceSums.compute(seq) { _, v -> v?.plus(price) ?: price }
}
}
return seqPriceSums.values.maxOrNull() ?: 0
}

fun next(nums: List<Int>): List<Int> {
return nums.map { it.next() }
}

fun Int.next(): Int {
var x = this
x = x.xor(x * 64).mod(16777216)
x = x.xor(x / 32).mod(16777216)
x = x.xor(x * 2048).mod(16777216)
return x
}

}
Loading

0 comments on commit 4d8b529

Please sign in to comment.