Skip to content

Commit 5ae780c

Browse files
committed
Rust Day4 part 2
1 parent 1c6cb3b commit 5ae780c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

2024/Rust/aoc2024/.vscode/launch.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,5 +117,20 @@
117117
"program": "${workspaceFolder:Rust}/target/debug/aoc2024",
118118
"preLaunchTask": "rust: cargo build"
119119
},
120+
{
121+
"type": "lldb",
122+
"request": "launch",
123+
"name": "Day 4 part 2",
124+
"args": [
125+
"--input-file",
126+
"${workspaceFolder:problems}/day4-1.txt",
127+
"--part-number",
128+
"2",
129+
"day4"
130+
],
131+
"cwd": "${workspaceFolder:Rust}",
132+
"program": "${workspaceFolder:Rust}/target/debug/aoc2024",
133+
"preLaunchTask": "rust: cargo build"
134+
},
120135
]
121136
}

2024/Rust/aoc2024/src/commands/day4.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ pub fn handle(input_file: std::path::PathBuf, part_number: u8) -> Result<(), io:
77

88
match part_number {
99
1 => part1(&contents),
10+
2 => part2(&contents),
1011
_ => Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid part number")),
1112
}
1213
}
@@ -117,3 +118,37 @@ fn part1(contents: &str) -> Result<(), io::Error> {
117118
println!("{}", count);
118119
Ok(())
119120
}
121+
122+
fn x_mases_beginning_at_line_and_character(lines: &Vec<Vec<char>>, line: usize, character: usize) -> usize {
123+
if line < 1 || line == lines.len() - 1 || character < 1 || character == lines[line].len() - 1 {
124+
return 0;
125+
}
126+
127+
let left_up = collect_characters_beginning_at_line_and_character(lines, line - 1, character - 1, 3, &Direction::RightDown);
128+
let left_down = collect_characters_beginning_at_line_and_character(lines, line + 1, character - 1, 3, &Direction::RightUp);
129+
let right_up = collect_characters_beginning_at_line_and_character(lines, line - 1, character + 1, 3, &Direction::LeftDown);
130+
let right_down = collect_characters_beginning_at_line_and_character(lines, line + 1, character + 1, 3, &Direction::LeftUp);
131+
let mut count = 0;
132+
let forward_mas = vec!['M', 'A', 'S'];
133+
let reverse_mas = forward_mas.iter().rev().cloned().collect::<Vec<char>>();
134+
if [left_up, left_down, right_up, right_down].iter().all(|direction| direction.eq(&forward_mas) || direction.eq(&reverse_mas)) {
135+
count += 1;
136+
}
137+
return count;
138+
}
139+
140+
fn part2(contents: &str) -> Result<(), io::Error> {
141+
let lines: Vec<Vec<char>> = contents
142+
.lines()
143+
.map(|line| line.chars().collect())
144+
.collect();
145+
146+
let mut count = 0;
147+
for line in 0..lines.len() {
148+
for character in 0..lines[line].len() {
149+
count += x_mases_beginning_at_line_and_character(&lines, line, character);
150+
}
151+
}
152+
println!("{}", count);
153+
Ok(())
154+
}

0 commit comments

Comments
 (0)