From fa26f694d8cf98272763952a698301ee9935c19e Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Thu, 26 Jun 2025 09:47:23 +0200 Subject: Added 2022, first few problems --- 2022/03/a.rs | 26 ++++++++++++++++++++++++++ 2022/03/b.rs | 29 +++++++++++++++++++++++++++++ 2022/03/common.rs | 7 +++++++ 3 files changed, 62 insertions(+) create mode 100644 2022/03/a.rs create mode 100644 2022/03/b.rs create mode 100644 2022/03/common.rs (limited to '2022/03') diff --git a/2022/03/a.rs b/2022/03/a.rs new file mode 100644 index 0000000..568546c --- /dev/null +++ b/2022/03/a.rs @@ -0,0 +1,26 @@ +mod common; +use common::*; + +fn get_rep_val(rucksack: &[u8]) -> i64 { + let mut seen = [false; 256]; + let mid = rucksack.len()/2; + for i in 0..mid { + seen[rucksack[i] as usize] = true; + } + for i in mid..rucksack.len() { + if seen[rucksack[i] as usize] { + return value(rucksack[i] as char); + } + } + panic!("Could not find repeated char"); +} + +fn main() { + let mut sum = 0; + let mut line = String::new(); + while std::io::stdin().read_line(&mut line).unwrap() > 0 { + sum += get_rep_val(line.as_bytes()); + line.clear(); + } + println!("{sum}"); +} diff --git a/2022/03/b.rs b/2022/03/b.rs new file mode 100644 index 0000000..89da764 --- /dev/null +++ b/2022/03/b.rs @@ -0,0 +1,29 @@ +mod common; +use common::*; + +fn get_rep_val(e: &[String; 3]) -> i64 { + let mut seen = [[false; 256]; 2]; + for i in 0..2 { + for c in e[i].chars() { + seen[i][c as usize] = true; + } + } + for c in e[2].chars() { + if seen[0][c as usize] && seen[1][c as usize] { + return value(c); + } + } + panic!("Could not find repeated char"); +} + +fn main() { + let mut sum = 0; + let mut lines: [String; 3] = Default::default(); + while std::io::stdin().read_line(&mut lines[0]).unwrap() > 0 { + let _ = std::io::stdin().read_line(&mut lines[1]); + let _ = std::io::stdin().read_line(&mut lines[2]); + sum += get_rep_val(&lines); + for l in &mut lines { l.clear(); } + } + println!("{sum}"); +} diff --git a/2022/03/common.rs b/2022/03/common.rs new file mode 100644 index 0000000..cf323f5 --- /dev/null +++ b/2022/03/common.rs @@ -0,0 +1,7 @@ +pub fn value(c: char) -> i64 { + match c { + 'a'..='z' => (c as i64) - ('a' as i64) + 1, + 'A'..='Z' => (c as i64) - ('A' as i64) + 27, + _ => panic!("Error: unexpected character '{}'", c) + } +} -- cgit v1.3