Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day 22: Monkey Market #19

Merged
merged 1 commit into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading