What on Earth is happening in this function?

I have been trying out Groovy on a few simple problems. I have solved this particular problem with many languages and have not had a problem previously, but this behaviour seems weird. In the function below (not original function, so should not constitute spoilers), running countWays(3,4) prints out the numbers 1 to 3 twice each to stderr, as I expected. However uncommenting the line between the print statements and re-running prints only 1 and 14. It’s as though the variable i is a global variable. However, I wrote some other test functions that behave normally and suggest that this is not the case. So what is happening? Any help appreciated.

def countWays(sc, r) {
    if (sc==0) {return 1}
    if (r==0) {return 0}

    cnt = 0
    for (i = 1; i < 13; i++) {
        if (i < sc+1) {
            if (sc==3) {
                System.err.println i
            }
            // d = countWays(sc-i, r-1)
            if (sc==3) {
                System.err.println i
            }
            c = 0
        }
    }
    return cnt
}

Hello, are you sure this is what you wanted to do?

Sorry. I didn’t mean to imply that this code was supposed to be directly used as-is solve the problem. I have stripped away functionality to try and isolate what the problem is. I do not understand what the current non-solution code is doing, and why uncommenting the one line should affect the output. Once I understand this, I ought to be able to understand why my original code was not working.

What other test functions have you written?

According to this page, all variables are created public by default in Groovy.

By the way, please edit your original message and format the code properly by using the </> button in the formatting toolbar.

1 Like

Thanks for the information. It turns out that my test functions weren’t doing what I thought they did, and all of the variables were in fact being treated as global or public. In this case, the variable i in the for loop is being updated when I call the countWays function again. To fix this, I just defined i as having local scope with

for (def i = 1; i < 13; i++) {

and the code started working as expected. I made a similar modification to my original code, and was able to successfully solve the Codingame problem.

1 Like