Skip to content

Commit 70c4969

Browse files
Solve Day 4 Part 1
1 parent 1e14dbb commit 70c4969

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

data/examples/04.txt

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
MMMSXXMASM
2+
MSAMXMSMSA
3+
AMXSXMAAMM
4+
MSAMASMSMX
5+
XMASAMXAMM
6+
XXAMMXXAMA
7+
SMSMSASXSS
8+
SAXAMASAAA
9+
MAMMMXMMMM
10+
MXMXAXMASX

src/bin/04.rs

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
advent_of_code::solution!(4);
2+
3+
pub fn part_one(input: &str) -> Option<u32> {
4+
let matrix: Vec<Vec<char>> = input.lines().map(|line| line.chars().collect()).collect();
5+
let m = matrix.len() as i32;
6+
let n = matrix[0].len() as i32;
7+
8+
let check_pos = |row: i32, col: i32| -> i32 {
9+
let xmas = "XMAS";
10+
let dirs = [
11+
(0, 1),
12+
(0, -1),
13+
(-1, 0),
14+
(1, 0),
15+
(-1, -1),
16+
(-1, 1),
17+
(1, -1),
18+
(1, 1),
19+
];
20+
21+
let mut result = 0;
22+
23+
'outer: for (dr, dc) in dirs {
24+
for i in 0..4 {
25+
let (r, c) = (row + (i * dr), col + (i * dc));
26+
if r >= 0 && c >= 0 && r < m && c < n {
27+
if xmas.chars().nth(i as usize).unwrap()
28+
!= matrix[r as usize][c as usize]
29+
{
30+
continue 'outer;
31+
}
32+
} else {
33+
continue 'outer;
34+
}
35+
}
36+
result += 1;
37+
}
38+
39+
return result;
40+
};
41+
42+
let mut count = 0;
43+
44+
for i in 0..m {
45+
for j in 0..n {
46+
count += check_pos(i, j);
47+
}
48+
}
49+
50+
Some(count as u32)
51+
}
52+
53+
pub fn part_two(input: &str) -> Option<u32> {
54+
None
55+
}
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
61+
#[test]
62+
fn test_part_one() {
63+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
64+
assert_eq!(result, Some(18));
65+
}
66+
67+
#[test]
68+
fn test_part_two() {
69+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
70+
assert_eq!(result, None);
71+
}
72+
}

0 commit comments

Comments
 (0)