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

1 Answer

0 votes
object AlphanumericSorter {

  /**
   * Assigns a sorting priority (category rank) to each character type.
   * Lower rank means the character group comes earlier.
   * * 1. lowercase letters  (a-z) -> 0
   * 2. uppercase letters  (A-Z) -> 1
   * 3. odd digits         (1,3,5,7,9) -> 2
   * 4. even digits        (0,2,4,6,8) -> 3
   */
  def getCategoryRank(c: Char): Int = {
    if (c.isLower) 0
    else if (c.isUpper) 1
    else if (c.isDigit) {
      // (c - '0') converts a digit Char to its integer representation
      if ((c - '0') % 2 != 0) 2 else 3
    }
    else 4 // Fallback for any non-alphanumeric characters
  }

  /**
   * Sorts the input string based on the custom rules:
   * lowercase -> uppercase -> odd digits -> even digits.
   * Within each category, characters are sorted in their natural ascending order.
   */
  def sortString(s: String): String = {
    // We leverage Scala's sortBy which accepts a function returning a Tuple.
    // Tuples are compared element-by-element:
    // First by category rank, then by the character's ASCII/Unicode value.
    s.sortBy(c => (getCategoryRank(c), c))
  }

  def main(args: Array[String]): Unit = {
    val input = "a2B3cD8f1Z0"
    val result = sortString(input)
    
    println(s"Sorted result: $result")
  }
}



/*
run:

Sorted result: acfBDZ13028

*/

 



answered Jul 14 by avibootz

Related questions

...