re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

I'm enjoying reading everyone's solutions. After doing last year's in Haskell I'm using Kotlin to try to improve my knowledge of the language and libraries. I'm also avoiding using an IDE, as auto-suggest and magic building don't teach you what's really going on under the hood.

package adventofcode2018.day1

import java.io.File

/** Infinitely repeat a sequence */
fun <T> Sequence<T>.repeat() = generateSequence { asIterable() }.flatten()

/** Like fold() but returns a sequence of all the accumulator values,
 *  not just the last one. `seq.scanl(i, f).last() == seq.fold(i, f)` */
fun <T, U> Sequence<T>.scanl(initial: U, f: (U, T) -> U): Sequence<U> {
    var acc: U = initial
    return map { x -> acc = f(acc, x); acc }
}

fun main(args: Array<String>) {
    val input: List<Int> = File("input.txt").readLines().map(String::toInt)

    // part 1
    val result = input.sum()
    println("Part 1 result: ${result}")

    // part 2
    val repeatedInput = input.asSequence().repeat()
    val accumulatedInput = repeatedInput.scanl(0, Int::plus)
    val unconsumed = accumulatedInput.dropWhile(mutableSetOf<Int>()::add)
    println("Part 2 result: ${unconsumed.first()}")
}

I know the idea is to avoid everyone's github but I'm writing notes on my solutions at github.com/neilgall/adventofcode2018

code of conduct - report abuse