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

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

/*
    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)

    Go's sort.Slice() with a custom comparator
    is the idiomatic and efficient way to do this.
*/

/// Returns category rank for sorting.
/// Lower rank = comes earlier.
func category(c rune) int {
    if c >= 'a' && c <= 'z' {
        return 0 // lowercase
    }
    if c >= 'A' && c <= 'Z' {
        return 1 // uppercase
    }
    if c >= '0' && c <= '9' {
        d := int(c - '0')
        if d%2 == 1 {
            return 2 // odd digits
        }
        return 3 // even digits
    }
    return 4 // fallback (should not happen for alphanumeric input)
}

/// Custom comparator for sorting runes
func compare(a, b rune) bool {
    ca := category(a)
    cb := category(b)

    if ca != cb {
        return ca < cb // sort by category first
    }
    return a < b // tie-breaker: natural order
}

func main() {
    s := "a2B3cD8f1Z0"

    // Convert string to slice of runes
    arr := []rune(s)

    // Sort using custom comparator
    sort.Slice(arr, func(i, j int) bool {
        return compare(arr[i], arr[j])
    })

    // Convert back to string
    result := string(arr)

    fmt.Println("Sorted result:", result)
}


/*
run:

Sorted result: acfBDZ13028

*/

 



answered Jul 14 by avibootz

Related questions

...