1
0
mirror of https://gitlab.com/MisterBiggs/aoc_2015-rust.git synced 2025-06-15 22:46:43 +00:00

Finished day 3

This commit is contained in:
Anson 2022-11-05 11:06:38 -06:00
parent dd087b4927
commit b1aaa2f7ae
3 changed files with 85 additions and 0 deletions

1
inputs/day3.txt Normal file

File diff suppressed because one or more lines are too long

82
src/day3.rs Normal file
View File

@ -0,0 +1,82 @@
use std::collections::HashSet;
use std::fs;
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub struct Point {
x: isize,
y: isize,
}
impl Point {
pub fn new(x: isize, y: isize) -> Self {
Self { x, y }
}
pub fn next_point(&mut self, dir: char) {
match dir {
'^' => self.y += 1,
'>' => self.x += 1,
'v' => self.y -= 1,
'<' => self.x -= 1,
_ => (),
};
}
}
pub fn run() {
println!("Day 3:");
let input = fs::read_to_string("./inputs/day3.txt").expect("Could not read file");
println!("\tPart 1: {}", part1(&input));
println!("\tPart 2: {}", part2(&input));
}
fn part1(directions: &String) -> usize {
let mut location = Point::new(0, 0);
let mut prev_locs = HashSet::new();
prev_locs.insert(location.clone());
for dir in directions.chars() {
location.next_point(dir);
prev_locs.insert(location.clone());
}
return prev_locs.len();
}
fn part2(directions: &String) -> usize {
let mut santa = Point::new(0, 0);
let mut robo = Point::new(0, 0);
let mut prev_locs = HashSet::new();
prev_locs.insert(santa.clone());
for (i, dir) in directions.chars().enumerate() {
if i % 2 == 0 {
santa.next_point(dir);
prev_locs.insert(santa.clone());
} else {
robo.next_point(dir);
prev_locs.insert(robo.clone());
}
}
return prev_locs.len();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_1() {
assert_eq!(part1(&">".to_string()), 2);
assert_eq!(part1(&"^>v<".to_string()), 4);
assert_eq!(part1(&"^v^v^v^v^v".to_string()), 2);
}
#[test]
fn test_part_2() {
assert_eq!(part2(&">>".to_string()), 2);
assert_eq!(part2(&"^>v<".to_string()), 3);
assert_eq!(part2(&"^v^v^v^v^v".to_string()), 11);
}
}

View File

@ -1,8 +1,10 @@
mod day1;
mod day2;
mod day3;
fn main() {
println!("Running Advent of Code 2021");
day1::run();
day2::run();
day3::run();
}