Skip to content

Instantly share code, notes, and snippets.

@neofight78
Created January 23, 2022 06:04
Show Gist options
  • Save neofight78/b68dd754ce4c8fef59f8dbf53711049c to your computer and use it in GitHub Desktop.
Save neofight78/b68dd754ce4c8fef59f8dbf53711049c to your computer and use it in GitHub Desktop.
Advent of Code 2020 - Day 3: Toboggan Trajectory
struct Map {
trees: Vec<Vec<bool>>,
width: usize,
height: usize,
}
impl From<&str> for Map {
fn from(grid: &str) -> Self {
let width = grid.lines().next().unwrap().len();
let height = grid.lines().count();
let trees = grid
.lines()
.map(|l| l.chars().map(|c| c == '#').collect())
.collect();
Self {
trees,
width,
height,
}
}
}
impl Index<(usize, usize)> for Map {
type Output = bool;
fn index(&self, index: (usize, usize)) -> &Self::Output {
let x = index.0 % self.width;
let y = index.1;
&self.trees[y][x]
}
}
fn main() {
let map = Map::from(INPUT);
let part1 = collisions((3, 1), &map);
let part2 = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
.iter()
.map(|&v| collisions(v, &map))
.product::<usize>();
println!("Part 1: {}", part1);
println!("Part 2: {}", part2);
}
fn collisions(vector: (usize, usize), map: &Map) -> usize {
let mut total = 0;
let mut pos = (0, 0);
while pos.1 < map.height {
if map[(pos)] {
total += 1;
}
pos = (pos.0 + vector.0, pos.1 + vector.1);
}
total
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment