day 4: part 1: rust

This commit is contained in:
Samuel Ortion 2024-12-04 11:48:21 +01:00
parent 858e44bf8a
commit f543fd930d
Signed by: sortion
GPG Key ID: 9B02406F8C4FB765
2 changed files with 102 additions and 0 deletions

View File

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

View File

@ -0,0 +1,96 @@
fn count_xmas(hay: Vec<Vec<char>>) -> u64 {
let target: Vec<char> = 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<char> = 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<char> = 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<char> = 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<char> = 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<char>> = Vec::new();
for line in std::io::stdin().lines() {
let line = line.unwrap();
let mut row: Vec<char> = Vec::new();
for chr in line.chars() {
row.push(chr);
}
hay.push(row);
}
let c = count_xmas(hay);
println!("{}", c);
Ok(())
}