Skip to content

Instantly share code, notes, and snippets.

@krikit
Created February 13, 2015 13:15
Show Gist options
  • Save krikit/5edc041114639616d226 to your computer and use it in GitHub Desktop.
Save krikit/5edc041114639616d226 to your computer and use it in GitHub Desktop.
object BotTrust extends App {
def line2list(line: String): List[(Char, Int)] = {
val itemList = line.split(" ").tail.toList
(for (i <- 0 until (itemList.size / 2)) yield (itemList(2 * i)(0), itemList(2 * i + 1).toInt)).toList
} //> line2list: (line: String)List[(Char, Int)]
def getTarget(list: List[(Char, Int)]): (Int, Int) = {
val oTarget = list.find(item => item._1 == 'O') match {
case None => -1
case Some(num) => num._2
}
val bTarget = list.find(item => item._1 == 'B') match {
case None => -1
case Some(num) => num._2
}
(oTarget, bTarget)
} //> getTarget: (list: List[(Char, Int)])(Int, Int)
def getTurn(list: List[(Char, Int)]): Char = list match {
case Nil => -1.toChar
case head :: tail => head._1
} //> getTurn: (list: List[(Char, Int)])Char
def simulate(list: List[(Char, Int)], oPos: Int, bPos: Int, tic: Int): Int = {
if (list.isEmpty) tic
else {
val (oTrg, bTrg) = getTarget(list)
val turn = getTurn(list)
var nextOPos = oPos
var nextBPos = bPos
var nextList = list
if (oTrg == oPos) {
if (turn == 'O') {
// push
nextList = list.tail
} else {
// stay, already on button
}
} else if (oTrg == -1) {
// stay, no more button to push
} else {
// move
nextOPos = if (oTrg > oPos) (oPos + 1) else (oPos - 1)
}
if (bTrg == bPos) {
if (turn == 'B') {
// push
nextList = list.tail
} else {
// stay, already on button
}
} else if (bTrg == -1) {
// stay, no more button to push
} else {
// move
nextBPos = if (bTrg > bPos) (bPos + 1) else (bPos - 1)
}
simulate(nextList, nextOPos, nextBPos, tic + 1)
}
} //> simulate: (list: List[(Char, Int)], oPos: Int, bPos: Int, tic: Int)Int
def solve(line: String): Int = simulate(line2list(line), 1, 1, 0)
//> solve: (line: String)Int
//////////
// main //
//////////
if (args.length > 0) Console.setIn(new java.io.FileInputStream(args(0)))
if (args.length > 1) Console.setOut(new java.io.FileOutputStream(args(1)))
for (t <- 1 to readInt) {
val line = readLine
println("Case #%d: %d".format(t, solve(line)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment