Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- advent_of_code::solution!(18);
- use advent_of_code::{Direction, MapIndex, NewIndex};
- use itertools::Itertools;
- #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
- struct Instruction {
- dir: Direction,
- step: usize,
- }
- fn parse_part_1(s: &str) -> Instruction {
- let (d, s, c) = s.split(" ").collect_tuple().unwrap();
- let dir = match d {
- "U" => Direction::North,
- "D" => Direction::South,
- "R" => Direction::East,
- "L" => Direction::West,
- _ => panic!("Wrong direction"),
- };
- Instruction {
- dir: dir,
- step: s.parse().unwrap(),
- }
- }
- fn parse_part_2(s: &str) -> Instruction {
- let (d, s, c) = s.split(" ").collect_tuple().unwrap();
- let hex: usize = usize::from_str_radix(c.strip_prefix("(#").unwrap().strip_suffix(")").unwrap(), 16).unwrap();
- let dir = match hex % 16 {
- 3 => Direction::North,
- 1 => Direction::South,
- 0 => Direction::East,
- 2 => Direction::West,
- _ => panic!("Wrong direction"),
- };
- Instruction {
- dir: dir,
- step: hex / 16,
- }
- }
- struct Case {
- instructions: Vec<Instruction>,
- }
- impl Case {
- fn solve(self: &Self) -> usize {
- let mut curr = (0 as i64, 0 as i64);
- let mut points = vec![curr];
- let mut length = 0;
- for inst in &self.instructions {
- let diff = inst.dir.diff_len(inst.step as i32);
- length += inst.step;
- curr = (curr.0 + diff.0 as i64, curr.1 + diff.1 as i64);
- points.push(curr);
- }
- points.push((0, 0));
- let mut result: i64 = 0;
- for i in 0..points.len() - 1 {
- let a = points[i];
- let b = points[i + 1];
- result += a.0 * b.1 - a.1 * b.0;
- }
- println!("Length: {length}");
- return (result.abs() / 2) as usize + length / 2 + 1;
- }
- }
- pub fn part_one(input: &str) -> Option<usize> {
- let case = Case {
- instructions: input.lines().map(parse_part_1).collect_vec()
- };
- Some(case.solve())
- }
- pub fn part_two(input: &str) -> Option<usize> {
- let case = Case {
- instructions: input.lines().map(parse_part_2).collect_vec()
- };
- Some(case.solve())
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_parse_part_2() {
- assert_eq!(Instruction {dir: Direction::East, step: 461937}, parse_part_2("R 6 (#70c710)"));
- }
- #[test]
- fn test_part_one() {
- let result = part_one(&advent_of_code::template::read_file("examples", DAY));
- assert_eq!(result, Some(62));
- }
- #[test]
- fn test_part_two() {
- let result = part_two(&advent_of_code::template::read_file("examples", DAY));
- assert_eq!(result, None);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment