-
-
Save theodoreLee/4804a504df88b727d703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileOutputStream | |
import scala.io.Source | |
object SwingingWild { | |
val INPUT = "A-small-practice.in" | |
val OUTPUT = INPUT.takeWhile(_ != '.') + ".out" | |
case class Vine(pos: Int, length: Int) | |
def main(args: Array[String]): Unit = { | |
val itr = Source.fromFile(INPUT).getLines() | |
val sets = itr.next().toInt | |
val writer = new FileOutputStream(OUTPUT) | |
// val writer = Console.out | |
try { | |
Console.withOut(writer) { | |
for (set <- 1 to sets) { | |
val vines = itr.next().toInt | |
val parse = for { | |
row <- (0 until vines).toList | |
} yield { | |
val line = itr.next().split(' ').map(_.toInt) | |
Vine(line(0), line(1)) | |
} | |
val maxDistance = itr.next().toInt | |
println(f"Case #${set}: ${solve(parse, maxDistance)}") | |
} | |
} | |
} finally { | |
writer.close() | |
} | |
} | |
def solve(list: List[Vine], maxDistance: Int): Boolean = { | |
def _solve(take: Vine, startPoint: Int, vines: List[Vine]): Boolean = { | |
val listVines = eligibleVines(startPoint, (take.pos - startPoint) * 2, vines) | |
listVines match { | |
case Nil => false | |
case _ => | |
val nextVine = listVines.maxBy(nextMaxPosition(startPoint, take, _)) | |
if (maxDistance <= nextMaxPosition(startPoint, take, nextVine)) { | |
true | |
} else { | |
_solve(nextVine, nextVine.pos - availableLength(take,nextVine), vines.filter(_.pos > nextVine.pos)) | |
} | |
} | |
} | |
_solve(list.head, 0, list.tail) | |
} | |
def eligibleVines(startPoint: Int, maxDistance: Int, vines: List[Vine]): List[Vine] = | |
vines.filter(_.pos <= startPoint + maxDistance) | |
def availableLength(vine: Vine, nextVine: Vine) = | |
Math.min(nextVine.pos - vine.pos, nextVine.length) | |
def nextMaxPosition(startPoint: Int, vine: Vine, nextVine: Vine): Int = | |
nextVine.pos + availableLength(vine,nextVine) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment