Skip to content

Instantly share code, notes, and snippets.

@Fokko
Created April 8, 2017 13:17
Show Gist options
  • Save Fokko/845be4401101313c151ff1d7d521a3c8 to your computer and use it in GitHub Desktop.
Save Fokko/845be4401101313c151ff1d7d521a3c8 to your computer and use it in GitHub Desktop.
package frl.driesprong
import scala.io.Source
// https://code.google.com/codejam/contest/3264486/dashboard#s=p0
object ProblemA extends App {
case class ProblemCase(pancakes: List[Boolean], K: Int)
val lines = Source.fromFile("/Users/fokkodriesprong/Downloads/A-small-attempt0.in").getLines().toList
def parseLine(parts: Array[String]): ProblemCase = {
val pancakes = parts(0).map(char => if (char == '+') true else false).toList
ProblemCase(pancakes, parts(1).toInt)
}
// Get rid of the number of tests
val cases = lines.tail.map(_.split(' ')).map(parseLine)
def solve(pancakes: List[Boolean], K: Int = 3, flips: Int = 0): Option[Int] = {
// If it is a minus, flip it!
if (pancakes.length < K) {
// Check if all remaining bools are true
if (pancakes.forall(bool => bool)) {
Some(flips)
} else {
None
}
} else {
if (!pancakes.head) {
val newPancakes = pancakes.take(K).map(!_) ++ pancakes.drop(K)
solve(newPancakes.tail, K, flips + 1)
}
else {
solve(pancakes.tail, K, flips)
}
}
}
def test(problemCase: ProblemCase, expected: Option[Int]): Unit = {
val result = solve(problemCase.pancakes, problemCase.K)
println(s"Case result $result")
assert(result == expected)
}
// ---+-++-
test(ProblemCase(List(false, false, false, true, false, true, true, false), 3), Some(3))
test(ProblemCase(List(true, true, true, true, true), 3), Some(0))
test(ProblemCase(List(false, true, false, true, false), 4), None)
val output = cases.map(problemCase => solve(problemCase.pancakes, problemCase.K)).zipWithIndex.map {
case (output: Option[Int], idx: Int) => s"Case #${idx + 1}: ${output.getOrElse("IMPOSSIBLE")}"
}.mkString("\n")
import java.io._
val pw = new PrintWriter(new File("/Users/fokkodriesprong/Desktop/problemA.txt"))
pw.write(output)
pw.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment