Skip to content

Instantly share code, notes, and snippets.

@darkfrog26
Last active December 1, 2018 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkfrog26/49c6e3117afe47ded833def07df27962 to your computer and use it in GitHub Desktop.
Save darkfrog26/49c6e3117afe47ded833def07df27962 to your computer and use it in GitHub Desktop.
package com.matthicks.aoc2018
import scala.annotation.tailrec
import scala.io.Source
object Day1 {
private lazy val data: List[Int] = {
Source.fromURL(getClass.getClassLoader.getResource("day1.txt")).getLines().toList.map(_.toInt)
}
def main(args: Array[String]): Unit = println(s"Part 1: ${part1(data)}, Part 2: ${part2(data)}")
def part1(changes: List[Int]): Int = changes.sum
def part2(changes: List[Int]): Int = recurse(Iterator.continually(changes).flatten)
@tailrec
private def recurse(iterator: Iterator[Int],
current: Int = 0,
states: Set[Int] = Set.empty): Int = current + iterator.next() match {
case state if states.contains(state) => state
case state => recurse(iterator, state, states + state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment