100-days-of-rust/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/lib.rs
2024-08-02 21:50:37 +02:00

38 lines
991 B
Rust

fn digit_to_chars(digit: char) -> Vec<char> {
match digit {
'2' => vec!['a', 'b', 'c'],
'3' => vec!['d', 'e', 'f'],
'4' => vec!['g', 'h', 'i'],
'5' => vec!['j', 'k', 'l'],
'6' => vec!['m', 'n', 'o'],
'7' => vec!['p', 'q', 'r', 's'],
'8' => vec!['t', 'u', 'v'],
'9' => vec!['w', 'x', 'y', 'z'],
_ => panic!(
"Character out of range: '{}' is not between '2' and '9'.",
digit
),
}
}
pub fn combination(digits: &str) -> Vec<String> {
let mut combinations: Vec<String> = vec![String::new()];
for d in digits.chars() {
let mut temp = Vec::new();
for c in combinations {
let chars = digit_to_chars(d);
for ch in chars {
temp.push(format!("{}{}", c, ch));
}
}
combinations = temp;
}
if combinations.len() == 1 {
vec![] as Vec<String>
} else {
combinations
}
}