Search code examples
scalarecursionint

How many breaks does it take to divide a chocolate completely?


CodeWars challenges again. Today I have a problem with this one:

"Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return a minimum number of breaks needed.

For example, if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks.

If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer."

For some reason, the output is constantly 0 no matter what sides of the chocolate bar I provide.

What I've already tried:

object breakChocolate {

    var result = 0

    def breakChocolate(n: Int, m: Int) = {

        var t = n*m
        var i =0
        def breaking(y:Int): Unit ={
            if (t ==0 || t ==1)
                result = i
            else {
                breaking(t%2)
                i +=1
            }
        }
        result
    }
}

Here are the tests:

Test Results: TestCases breakChocolate(5, 5) should return 24 Test Failed

0 was not equal to 24 Stack Trace Completed in 38ms breakChocolate(7, 4) should return 27 Test Failed

0 was not equal to 27 Stack Trace Completed in 1ms Completed in 76ms


Solution

  • To solve this problem you don't need recursion at all. Consider the special case of chocolate plate: (1 x n). To divide this plate completely you need (n-1) breaks. Now you have plate m x n. To divide it into m pieces of form (1 x n) you need (m-1) breaks. So the total number of breaks is

    (m-1) + m*(n-1) ~ 
    m - 1 + m*n - m ~ 
    m*n - 1