day 4: part 1: rust
This commit is contained in:
parent
858e44bf8a
commit
f543fd930d
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "part1"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
|
@ -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(())
|
||||
}
|
Loading…
Reference in New Issue