Tony Davidson
Tony Davidson

Reputation: 23

groovy if statement returning wrong answer

List sortList(List list1){
    def sorted = []
    while(list1){
        def lowest
        for(n in list1){
            if(!lowest || lowest == null || n < lowest) lowest = n
        }
        sorted.add(sorted.size, lowest)
        list1.remove(list1.indexOf(lowest))  
    }
    return sorted
}

def odds = [0,-6,2]
assert sortList(odds) == [-6,0,2]

The above code sorts integers. It was a solution to a problem set for kids in CoderDojo. It correctly sorts a list of integers, however if there is 0 in the list the conditional statement returns true when n < lowest, (when n == 2 and lowest ==0). Below is the output to the console when the code is run.

Caught: Assertion failed:        

assert sortList(odds) == [-6,0,2]    
       |        |     |            
       |        []    false
       [-6, 2, 0]               

Assertion failed:          

assert sortList(odds) == [-6,0,2]                  
       |        |     |                            
       |        []    false                        
       [-6, 2, 0]                                  

        at TonyZeroTest.run(TonyZeroTest.groovy:19)
        at RunScript.run(RunScript.groovy:66)


Process exited with code: 1

Any help to understand this would be appreciated.

Upvotes: 1

Views: 322

Answers (2)

billjamesdev
billjamesdev

Reputation: 14642

The problem exists in this line:

if(!lowest || lowest == null || n < lowest) lowest = n

And occurs when lowest = 0. I'm not sure why you would test !lowest AND lowest == null. When lowest is 0, !lowest is true, and you'll re-assign lowest to whatever value n is, regardless of it being less than the current lowest (0).

Simply remove the !lowest condition, and you should be good.

For more on why !lowest == true, check here: http://groovy-lang.org/semantics.html#Groovy-Truth

Upvotes: 3

Joseph Young
Joseph Young

Reputation: 2795

Moved my comment to answer:

I have no idea how groovy works, but I'm going to assume that !lowest evaluates !0 => true, so when the previous value is 0, the next value to be checked becomes the lowest.

Perhaps intialise lowest to be null and then only check if it's null or lower:

def lowest = null
for(n in list1){
    if(lowest == null || n < lowest) lowest = n
}

Upvotes: 0

Related Questions