If you just need a simple comparison of numbers, you can do it like this.
directions.sortWith(Comparator { lhs, rhs -> val i1 = lhs.toInt() val i2 = rhs.toInt() when { i1 < i2 -> -1 i1 > i2 -> 1 else -> 0 } })
Like a hotkey , the above code can be replaced with an almost identical implementation, which looks much simpler.
directions.sortBy { it.toInt() }
The general version of this algorithm is called alphabetical sorting and is described in detail here . I made a Kotlin port of this algorithm that you can use. This is harder than you need, but it will solve your problem.
class AlphanumComparator : Comparator<String> { override fun compare(s1: String, s2: String): Int { var thisMarker = 0 var thatMarker = 0 val s1Length = s1.length val s2Length = s2.length while (thisMarker < s1Length && thatMarker < s2Length) { val thisChunk = getChunk(s1, s1Length, thisMarker) thisMarker += thisChunk.length val thatChunk = getChunk(s2, s2Length, thatMarker) thatMarker += thatChunk.length // If both chunks contain numeric characters, sort them numerically. var result: Int if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) { // Simple chunk comparison by length. val thisChunkLength = thisChunk.length result = thisChunkLength - thatChunk.length // If equal, the first different number counts. if (result == 0) { for (i in 0..thisChunkLength - 1) { result = thisChunk[i] - thatChunk[i] if (result != 0) { return result } } } } else { result = thisChunk.compareTo(thatChunk) } if (result != 0) { return result } } return s1Length - s2Length } private fun getChunk(string: String, length: Int, marker: Int): String { var current = marker val chunk = StringBuilder() var c = string[current] chunk.append(c) current++ if (isDigit(c)) { while (current < length) { c = string[current] if (!isDigit(c)) { break } chunk.append(c) current++ } } else { while (current < length) { c = string[current] if (isDigit(c)) { break } chunk.append(c) current++ } } return chunk.toString() } private fun isDigit(ch: Char): Boolean { return '0' <= ch && ch <= '9' } }
To use this Comparator just a call
directions.sortWith(AlphanumComparator())
If you do not need to code it in Kotlin, you can simply take the original version of Java on the Dave Koelle page . And a version of the Kotlin algorithm can also be found on GitHub .
source share