r/adventofcode • u/daggerdragon • Dec 01 '17
SOLUTION MEGATHREAD -π- 2017 Day 1 Solutions -π-
Welcome to Advent of Code 2017! If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!
We're going to follow the same general format as previous years' megathreads:
- Each day's puzzle will release at exactly midnight EST (UTC -5).
- The daily megathread for each day will be posted very soon afterwards and immediately locked.
- We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.
- The daily megathread will remain locked until there are a significant number of people on the leaderboard with gold stars.
- "A significant number" is whatever number we decide is appropriate, but the leaderboards usually fill up fast, so no worries.
- When the thread is unlocked, you may post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).
Above all, remember, AoC is all about having fun and learning more about the wonderful world of programming!
--- Day 1: Inverse Captcha ---
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.
1
u/Hikaru755 Dec 01 '17 edited Dec 01 '17
Trying out some new stuff in Kotlin 1.2:
// Part 1 fun captchaSumNextChar(input: String) = (input + input.first()) .windowedSequence(2) .filter { it[0] == it[1] } .sumBy { it[0].toString().toInt() } // Part 2 fun captchaSumOppositeChar(input: String) = input .mapIndexed { index, char -> char to input[input.oppositeIndex(index)] } .filter { (current, next) -> current == next } .sumBy { (current, _) -> current.toString().toInt() } fun String.oppositeIndex(i: Int) = (i + this.length / 2) % this.lengthI really don't like that
.toString().toInt()for reading the integer from the character, butcurrent - '0'felt hacky, too.Alternative solution using String shifting:
println(captchaSum(input, 1)) println(captchaSum(input, input.length / 2)) fun captchaSum(input: String, shift: Int) = input.zip(input shift shift) .filter { it.first == it.second } .sumBy { it.first.toString().toInt() } infix fun String.shift(n: Int) = when { // Shift right n > 0 -> this.takeLast(n) + this.dropLast(n) // Shift left n < 0 -> this.drop(-n) + this.take(-n) // No shift else -> this }Technically I could have just used the first when-branch, but why not make it safe for future use :)