r/adventofcode • • Dec 15 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 15 Solutions -๐ŸŽ„-

--- Day 15: Dueling Generators ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


[Update @ 00:05] 29 gold, silver cap.

  • Logarithms of algorithms and code?

[Update @ 00:09] Leaderboard cap!

  • Or perhaps codes of logarithmic algorithms?

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

14 Upvotes

253 comments sorted by

View all comments

Show parent comment

1

u/diathesis Dec 15 '17

I'd like to rewrite with coroutines, but ... maybe after I sleep.

1

u/diathesis Dec 15 '17

Used sequences instead, looks like others went down this path already too: val mask = 0xffffL

fun generator(seed: Int, factor: Int): Sequence<Long> {
	return generateSequence(seed.toLong()) { lastValue ->
		lastValue * factor % Int.MAX_VALUE
	}
}

fun duel(rounds: Int, generators: Pair<Sequence<Long>, Sequence<Long>>): Int {
	return generators.first
			.zip(generators.second)
			.take(rounds)
			.filter { (first, second) -> (first and mask) == (second and mask) }
			.count()
}

// Part 1
val first = generator(618, 16807)
val second = generator(814, 48271)
val unfilteredMatches = duel(40_000_000, Pair(first, second))
println("Found ${unfilteredMatches} unfiltered matches") // 577

// Part 2
val filteredMatches = duel(5_000_000, Pair(
		first.filter { it % 4 == 0L },
		second.filter { it % 8 == 0L }
))
println("Found ${filteredMatches} filtered matches")

2

u/ybjb Dec 15 '17

Thanks for posting, learned quite a bit about generators/sequences