Skip to content

Instantly share code, notes, and snippets.

@segomin
Created March 8, 2024 12:20
Show Gist options
  • Save segomin/0897b660cff3ebef02dbf10de2ba64be to your computer and use it in GitHub Desktop.
Save segomin/0897b660cff3ebef02dbf10de2ba64be to your computer and use it in GitHub Desktop.
cut chocolate
import scala.annotation.tailrec
case class Chocolate(height: Int, width: Int) {
def cut: Option[(Chocolate, Chocolate)] = {
if (height == 1 && width == 1) return None
val (hs, ws) = (height, width) match {
case (1, w) => ((1, 1), split(width))
case (h, 1) => (split(height), (1, 1))
case _ => if (randomBool) (split(height), (width, width)) else ((height, height), split(width))
}
Some(Chocolate(hs._1, ws._1), Chocolate(hs._2, ws._2))
}
private def split(thick: Int): (Int, Int) = {
val one = thick / 2
(one, thick - one)
}
private def randomBool: Boolean = scala.util.Random.nextBoolean()
}
@main def main: Unit =
@tailrec
def cutChocolates(chocolates: List[Chocolate], cut: Int): Int = {
if (chocolates.isEmpty) cut
else {
val (choco, rest) = (chocolates.head, chocolates.tail)
choco.cut match {
case Some((c1, c2)) => cutChocolates(c1 :: c2 :: rest, cut + 1)
case None => cutChocolates(rest, cut)
}
}
}
List((4, 3), (4, 4), (100, 123), (123, 100))
.foreach { case (h, w) =>
val chocolates = List(Chocolate(h, w))
val result = cutChocolates(chocolates, 0)
assert(result == h * w - 1, s"$h x $w: $result")
println(s"$h x $w => ${result}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment