From f543fd930d71348d5cf3e047877bb8ffcf337d35 Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Wed, 4 Dec 2024 11:48:21 +0100 Subject: [PATCH] day 4: part 1: rust --- 2024/days/04/part1/Cargo.toml | 6 +++ 2024/days/04/part1/src/main.rs | 96 ++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 2024/days/04/part1/Cargo.toml create mode 100644 2024/days/04/part1/src/main.rs diff --git a/2024/days/04/part1/Cargo.toml b/2024/days/04/part1/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2024/days/04/part1/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/days/04/part1/src/main.rs b/2024/days/04/part1/src/main.rs new file mode 100644 index 0000000..a7d1e06 --- /dev/null +++ b/2024/days/04/part1/src/main.rs @@ -0,0 +1,96 @@ +fn count_xmas(hay: Vec>) -> u64 { + let target: Vec = vec!['X', 'M', 'A', 'S']; + let mut count: u64 = 0; + for i in 0..hay.len() { + for j in 0..hay[i].len() { + // Top to bottom + let mut needle: Vec = Vec::new(); + for k in 0..target.len() { + if i + k >= hay.len() { + break; + } + let letter = hay[i+k][j]; + needle.push(letter); + } + if needle.len() == target.len() { + if needle == target { + count += 1; + } + needle.reverse(); + if needle == target { + count += 1; + } + } + // Left to right + let mut needle: Vec = Vec::new(); + for k in 0..target.len() { + if j + k >= hay[i].len() { + break; + } + let letter = hay[i][j+k]; + needle.push(letter); + } + if needle.len() == target.len() { + if needle == target { + count += 1; + } + needle.reverse(); + if needle == target { + count += 1; + } + } + // Main Diagonal + let mut needle: Vec = Vec::new(); + for k in 0..target.len() { + if j + k >= hay[i].len() || i + k >= hay.len() { + break; + } + let letter = hay[i+k][j+k]; + needle.push(letter); + } + if needle.len() == target.len() { + if needle == target { + count += 1; + } + needle.reverse(); + if needle == target { + count += 1; + } + } + // Secondary diagonal + let mut needle: Vec = Vec::new(); + for k in 0..target.len() { + if j < k || i + k >= hay.len() { + break; + } + let letter = hay[i+k][j-k]; + needle.push(letter); + } + if needle.len() == target.len() { + if needle == target { + count += 1; + } + needle.reverse(); + if needle == target { + count += 1; + } + } + } + } + count +} + +fn main() -> std::io::Result<()> { + let mut hay: Vec> = Vec::new(); + for line in std::io::stdin().lines() { + let line = line.unwrap(); + let mut row: Vec = Vec::new(); + for chr in line.chars() { + row.push(chr); + } + hay.push(row); + } + let c = count_xmas(hay); + println!("{}", c); + Ok(()) +} \ No newline at end of file