/*
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)
Rust's Vec<char>.sort_by() with a custom comparator
is the idiomatic and efficient way to do this.
*/
/// Returns category rank for sorting.
/// Lower rank = comes earlier.
fn category(c: char) -> u8 {
if c.is_ascii_lowercase() {
return 0; // lowercase
}
if c.is_ascii_uppercase() {
return 1; // uppercase
}
if c.is_ascii_digit() {
let d = c.to_digit(10).unwrap();
return if d % 2 == 1 { 2 } else { 3 }; // odd → 2, even → 3
}
4 // fallback (should not happen for alphanumeric input)
}
/// Custom comparator for sorting characters
fn compare_chars(a: &char, b: &char) -> std::cmp::Ordering {
let ca = category(*a);
let cb = category(*b);
if ca != cb {
return ca.cmp(&cb); // sort by category first
}
a.cmp(b) // tie-breaker: natural order
}
fn main() {
let s: &str = "a2B3cD8f1Z0";
// Convert string to vector of chars
let mut arr: Vec<char> = s.chars().collect();
// Sort using custom comparator
arr.sort_by(compare_chars);
// Convert back to string
let result: String = arr.iter().collect();
println!("Sorted result: {}", result);
}
/*
run:
Sorted result: acfBDZ13028
*/