Wrote program for Day 8

This commit is contained in:
Mariano Riefolo 2024-08-02 21:50:37 +02:00
parent 1fb8530cbc
commit 6ee3c88c30
4 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "day8"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,37 @@
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
}
}

View File

@ -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
);
}

View File

@ -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<String>);
}
#[test]
fn example3() {
assert_eq!(combination("2"), vec!["a", "b", "c"]);
}