diff --git a/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/Cargo.toml b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/Cargo.toml new file mode 100644 index 0000000..cc06d1e --- /dev/null +++ b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day8" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/lib.rs b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/lib.rs new file mode 100644 index 0000000..b5c85ed --- /dev/null +++ b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/lib.rs @@ -0,0 +1,37 @@ +fn digit_to_chars(digit: char) -> Vec { + 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 { + let mut combinations: Vec = 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 + } else { + combinations + } +} diff --git a/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/main.rs b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/main.rs new file mode 100644 index 0000000..ccdb16f --- /dev/null +++ b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/src/main.rs @@ -0,0 +1,21 @@ +use std::io::{self, Write}; + +use day8::combination; + +fn main() { + let mut buffer = String::new(); + + print!("Insert the digits: "); + io::stdout().flush().expect("Failed to flush stdout."); + + io::stdin() + .read_line(&mut buffer) + .expect("Failed to read the digits."); + + let combinations = combination(buffer.trim()); + + println!( + "Those are all the possible combinations: {:?}", + combinations + ); +} diff --git a/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/tests/examples.rs b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/tests/examples.rs new file mode 100644 index 0000000..cba054d --- /dev/null +++ b/Week-02/Day-08_Letter-Combinations-Of-A-Phone-Number/day8/tests/examples.rs @@ -0,0 +1,19 @@ +use day8::combination; + +#[test] +fn example1() { + assert_eq!( + combination("23"), + vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] + ); +} + +#[test] +fn example2() { + assert_eq!(combination(""), vec![] as Vec); +} + +#[test] +fn example3() { + assert_eq!(combination("2"), vec!["a", "b", "c"]); +}