Skip to content

Instantly share code, notes, and snippets.

@theodoreLee
Created February 13, 2015 17:14
Show Gist options
  • Save theodoreLee/172da0a901a651a21323 to your computer and use it in GitHub Desktop.
Save theodoreLee/172da0a901a651a21323 to your computer and use it in GitHub Desktop.
code jam(https://code.google.com/codejam/contest/975485/dashboard). scala 스럽지 않음.. 리펙토링 필요함..
/**
* Created by Teddy on 2015. 2. 14..
*/
case class Simulator(turnOrder: List[String], blue: Bot, orange: Bot) {
private var isButtonPushed = false
def run: Int = {
def simulate(time: Int, turns: List[String], b: Bot, o: Bot): Int = turns match {
case Nil => time
case currentTurn :: xs =>
// print(time + " : ")
val newB = b.work(currentTurn, this)
// print(", ")
val newO = o.work(currentTurn, this)
// println("")
if (isButtonPushed) {
isButtonPushed = false
simulate(time + 1, xs, newB, newO)
} else simulate(time + 1, turns, newB, newO)
}
simulate(0, turnOrder, blue, orange)
}
def pushButton {
isButtonPushed = true
}
}
case class Bot(codeName: String, location: Int, jobList: List[Int]) {
def work(currentTurn: String, simulator: Simulator): Bot = jobList match {
case Nil =>
// print(s"$codeName finished work!")
this
case pos :: xs if (pos != location) =>
// print(s"$codeName is moving($location -> $pos)")
Bot(codeName, moveTo(pos), jobList)
case pushState :: xs if (currentTurn == codeName) =>
// print(s"$codeName pushes the button")
simulator.pushButton
Bot(codeName, location, xs)
case stayState =>
// print(s"$codeName is staying")
this
}
def moveTo(head: Int) = if (head - location > 0) location + 1 else location - 1
}
object BotTrust extends App {
def minTime(order: List[(String, Int)]): Int = {
// println(order)
val (blueOrder, orangeOrder) = order.partition(_._1 == "B")
val blue = Bot("B", 1, blueOrder.map(_._2))
val orange = Bot("O", 1, orangeOrder.map(_._2))
Simulator(order.map(_._1), blue, orange).run
}
/**
* @note refers to https://gist.github.com/sungkmi/69b01c67378060d19511
* @param lineIn
* @param lineOut
* @return
*/
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val order = lineIn.next().split(' ').tail.grouped(2).map { case Array(bot, button) => (bot, button.toInt) }.toList
lineOut(s"Case #$i: ${minTime(order)}")
}
val writer = new java.io.PrintWriter("A-large-practice.out.txt")
try {
process(io.Source.fromFile("A-large-practice.in").getLines) { s =>
writer.println(s)
writer.flush()
}
} finally {
writer.flush(); writer.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment