Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created August 22, 2014 13:30
Show Gist options
  • Save sungkmi/7607e9ea60e3a8fa7753 to your computer and use it in GitHub Desktop.
Save sungkmi/7607e9ea60e3a8fa7753 to your computer and use it in GitHub Desktop.
object MeetAndParty extends App {
def locateParty(rectangularAreas: IndexedSeq[(Int, Int, Int, Int)]): (Int, Int, BigInt) = {
val houses = for {
(x1, y1, x2, y2) <- rectangularAreas
x <- x1 to x2
y <- y1 to y2
} yield (x, y)
val (xs, ys) = houses.unzip
def median(xs: IndexedSeq[Int]): (Int, Int) = {
val sorted = xs.sorted
val mIndex = xs.size / 2
if (xs.size % 2 == 0) (sorted(mIndex - 1), sorted(mIndex))
else (sorted(mIndex), sorted(mIndex))
}
def medianDist(x: Int, median: (Int, Int)): Int = {
val (a, b) = median
if (x < a) a - x
else if (a <= x && x < b) 0
else x - b
}
val (xMed, yMed) = (median(xs), median(ys))
val (x, y) = houses.minBy {
case (x, y) => (medianDist(x, xMed) + medianDist(y, yMed), x, y)
}
def dist(xs: IndexedSeq[Int], x: Int): BigInt = xs.map(math abs _ - x).map(BigInt.apply).sum
(x, y, dist(xs, x) + dist(ys, y))
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) = {
for (i <- 1 to lineIn.next().toInt) {
val b = lineIn.next().toInt
val rectangularAreas = Vector.fill(b) {
val Array(x1, y1, x2, y2) = lineIn.next split ' ' map (_.toInt)
(x1, y1, x2, y2)
}
val (x, y, d) = locateParty(rectangularAreas)
lineOut(s"Case #$i: $x $y $d")
}
}
val writer = new java.io.PrintWriter("b.small.out.ref")
try {
process(io.Source.fromFile("B-small-practice.in").getLines)(writer.println)
} finally {
writer.flush(); writer.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment