Skip to content

Instantly share code, notes, and snippets.

@paralax
Last active August 29, 2015 14:21
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 paralax/18ee49196d0a3e49e9c1 to your computer and use it in GitHub Desktop.
Save paralax/18ee49196d0a3e49e9c1 to your computer and use it in GitHub Desktop.
reddit 214H solution
import scala.io.Source
import scala.math._
def dist(x:(Double, Double), y:(Double, Double)): Double =
sqrt(pow(x._1-y._1, 2.0) + pow(x._2-y._2, 2.0))
// yields a 3-tuple: distance to travel, closest treat pos, remaining treats
def best(pos:(Double, Double), treats:List[(Double,Double)]): (Double, (Double, Double), List[(Double,Double)])= {
val sorted = treats.map(x => (dist(pos, x),x)).sortBy(_._1)
(sorted.head._1, sorted.head._2, sorted.tail.map(_._2))
}
def read(): List[(Double,Double)] =
Source.fromFile("/tmp/input.txt").getLines.toList.tail.map(_.split(" ").map(_.toDouble)).map(x=>(x(0), x(1))).toList
def main(): Double = {
def loop(pos:(Double,Double), treats:List[(Double, Double)], dist: Double): Double = {
treats match {
case Nil => dist
case _ => val (l, newtreat, remaining) = best(pos, treats)
loop(newtreat, remaining, dist+l)
}
}
loop((0.5, 0.5), read(), 0.0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment