Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in Kotlin

1 Answer

0 votes
/*
    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

*/

 



answered Jul 14 by avibootz

Related questions

...