1
Fork 0
advent-of-code/source/year_2020/day_03/mod.rs

51 lines
1.1 KiB
Rust
Raw Permalink Normal View History

2024-01-14 21:04:10 +00:00
//! Day 03 of 2020.
2022-10-03 16:02:40 +00:00
use crate::prelude::*;
2024-01-14 21:04:10 +00:00
/// Get the solution for day 03 of 2020.
2022-10-03 16:02:40 +00:00
pub fn solution() -> Solution {
Solution::new(Day::new(3, 2020), part_1, part_2)
.with_expected(198, 5140884672_i64)
}
2024-01-14 21:04:10 +00:00
/// Generic solver that takes in a horizontal and vertical movement for the
/// slope.
2022-10-03 16:02:40 +00:00
fn solve(data: &str, (horizontal, vertical): (usize, usize)) -> usize {
let line_length = data.find('\n').unwrap();
let mut result = 0;
let mut x_position = 0;
for (y_position, line) in data.lines().enumerate() {
if y_position % vertical != 0 {
continue;
}
if line.chars().nth(x_position) == Some('#') {
result += 1;
}
x_position += horizontal;
if x_position >= line_length {
x_position -= line_length;
}
}
result
}
2024-01-14 21:04:10 +00:00
/// The logic to solve part one.
2022-10-03 16:02:40 +00:00
fn part_1(input: &str) -> Result<String> {
Ok(solve(input, (3, 1)).to_string())
}
2024-01-14 21:04:10 +00:00
/// The logic to solve part two.
2022-10-03 16:02:40 +00:00
fn part_2(input: &str) -> Result<String> {
Ok(
[(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
.into_iter()
.map(|increment| solve(input, increment))
.product::<usize>()
.to_string(),
)
}