Created
March 8, 2024 12:20
-
-
Save segomin/0897b660cff3ebef02dbf10de2ba64be to your computer and use it in GitHub Desktop.
cut chocolate
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 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