Skip to content

Instantly share code, notes, and snippets.

@pakaufmann
Last active December 1, 2016 08:46
Show Gist options
  • Save pakaufmann/cd9f68ea801879d5341131b57fa16c39 to your computer and use it in GitHub Desktop.
Save pakaufmann/cd9f68ea801879d5341131b57fa16c39 to your computer and use it in GitHub Desktop.
object Day1 extends Challenge {
override def runFirst(): Unit = {
val startPosition = Position.start
val endPosition = loadInput().foldLeft(startPosition) {
case (p, ("R", l)) =>
p.turnRight().walk(l.toLong)
case (p, ("L", l)) =>
p.turnLeft().walk(l.toLong)
}
println(startPosition.distanceTo(endPosition))
}
override def runSecond(): Unit = {
val startPosition = Position.start
val positions = loadInput().foldLeft(Seq(startPosition)) {
case (p, ("R", l)) =>
p.init ++ 1.to(l.toInt).scanLeft(p.last.turnRight())((a, _) => a.walk(1))
case (p, ("L", l)) =>
p.init ++ 1.to(l.toInt).scanLeft(p.last.turnLeft())((a, _) => a.walk(1))
}
def findFirstDuplicate(list: List[Position]): Option[Position] = list match {
case head :: tail if tail.exists(p => p.x == head.x && p.y == head.y) =>
Some(head)
case head :: tail =>
findFirstDuplicate(tail)
}
findFirstDuplicate(positions.toList).foreach(d => println(d.distanceTo(startPosition)))
}
def loadInput(): Array[(String, String)] =
loadFile("day1.txt").mkString.split(',').map(_.trim.splitAt(1))
object Direction extends Enumeration {
type Direction = Value
val North = Value(0)
val East = Value(1)
val South = Value(2)
val West = Value(3)
}
case class Position(direction: Direction, x: Long, y: Long) {
def distanceTo(position: Position): Long = (position.x - x).abs + (position.y - y).abs
def turnLeft(): Position = this.copy(Direction((((direction.id - 1) % 4) + 4) % 4))
def turnRight(): Position = this.copy(Direction((direction.id + 1) % 4))
def walk(steps: Long): Position =
this.direction match {
case Direction.North => this.copy(y = y + steps)
case Direction.East => this.copy(x = x + steps)
case Direction.South => this.copy(y = y - steps)
case Direction.West => this.copy(x = x - steps)
}
}
case object Position {
def start: Position = Position(Direction.North, 0, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment