/*
We want to sort characters in this strict order:
1. lowercase letters (a–z)
2. uppercase letters (A–Z)
3. odd digits (1,3,5,7,9)
4. even digits (0,2,4,6,8)
Strategy:
---------
Assign each character a "category rank" and sort by:
(category rank, natural character order)
Kotlin's sortedWith() + compareBy() is the idiomatic way
to implement custom sorting.
*/
/// Returns category rank for sorting.
/// Lower rank = comes earlier.
fun category(c: Char): Int {
return when {
c.isLowerCase() -> 0 // lowercase
c.isUpperCase() -> 1 // uppercase
c.isDigit() -> {
val d: Int = c.digitToInt()
if (d % 2 == 1) 2 else 3 // odd → 2, even → 3
}
else -> 4 // fallback (should not happen)
}
}
/// Sort characters using a tuple key:
/// (category rank, natural character order)
fun sortAlphaNumeric(s: String): String {
return s.toList()
.sortedWith(compareBy({ category(it) }, { it }))
.joinToString("")
}
fun main() {
val s: String = "a2B3cD8f1Z0"
val result: String = sortAlphaNumeric(s)
println("Sorted result: $result")
}
/*
run:
Sorted result: acfBDZ13028
*/