kotlin-koans icon indicating copy to clipboard operation
kotlin-koans copied to clipboard

Task i.10 expects list in descending order instead of ascending

Open beheist opened this issue 7 years ago • 2 comments

According to the java doc, the java.util.Comparator should do the follwing:

Compares its two arguments for order.  Returns a negative integer,
zero, or a positive integer as the first argument is less than, equal
to, or greater than the second.

The current suggested resolution is:

Collections.sort(arrayList, object : Comparator<Int> {
    override fun compare(x: Int, y: Int) = y - x
})

which does the opposite - it returns a positive number if the first argument is less than the second, and a negative if the first argument is greater than the second. I suggest changing the solution to:

Collections.sort(arrayList, object : Comparator<Int> {
    override fun compare(x: Int, y: Int) = x - y
})

and the test to:

class N10ObjectExpressionsKtTest {
    @Test fun testSort() {
        assertEquals(listOf(1, 2, 5), task10())
    }
}

beheist avatar Sep 21 '17 00:09 beheist

I initially thought the same thing as I wanted my compare function to match the definition in the Comparator interface.

However, the problem TODO does specifically state to sort in decending order:

Add an object expression that provides a comparator to sort a list in a descending order using 'java.util.Collections' class.

One way to maintain the true contract of compare, but without modifying the problem is to use the reversed method:

class MyComparator : Comparator<Int> {
    override fun compare(x: Int, y: Int) = x - y
}

fun task10(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, MyComparator().reversed())
    return arrayList
}

daj avatar Dec 24 '17 04:12 daj

Hi, as I know (not sure just from Kotlin 1.1), all arguments of compare() method are nullable. It means that method should be fun compare(x: Int?, y: Int?): Int. Thus, we should check these arguments for nullability first.

trietbui85 avatar Mar 30 '18 04:03 trietbui85