diff --git a/src/day18.rs b/src/day18.rs index ba6cb64..351f157 100644 --- a/src/day18.rs +++ b/src/day18.rs @@ -42,8 +42,20 @@ impl DirectionConvertable for &str { } } -#[aoc_generator(day18)] -fn parse(input: &str) -> Vec { +impl DirectionConvertable for i32 { + fn to_direction(&self) -> Direction { + match self { + 3 => Direction::Up, + 1 => Direction::Down, + 2 => Direction::Left, + 0 => Direction::Right, + _ => panic!("Invalid Direction") + } + } +} + +#[aoc_generator(day18, part1)] +fn parse_part1(input: &str) -> Vec { let steps = input.lines() .map(|line| { let mut line = line.split(' '); @@ -67,7 +79,6 @@ fn part1(steps: &Vec) -> i32 { area -= win[0].x * win[1].y; } - // Due to how area works in math, half of the premitier spots are included in the area calculation. (area / 2) + (verticies.len() as i32 / 2) + 1 } @@ -96,10 +107,43 @@ fn get_verticies(steps: &Vec) -> Vec { verticies } -// #[aoc(day18, part2)] -// fn part2(steps: &Vec) -> i32 { -// todo!() -// } +#[aoc_generator(day18, part2)] +fn parse_part2(input: &str) -> Vec { + let steps = input.lines() + .map(|line| { + let line = line.split(' '); + parse_hex(line.last().unwrap()) + }).collect::>(); + + steps +} + +fn parse_hex(hex: &str) -> Step { + let hex = hex.trim_matches(['(', ')', '#'].as_slice()); + let length = "0".to_string() + &hex[0..5]; + let length = u32::from_str_radix(&length, 16).expect("Cannot parse Hex value"); + + let dir = hex.chars().last().unwrap().to_string().parse::().unwrap().to_direction(); + + Step { + dir, + length: length as i32 + } +} + +#[aoc(day18, part2)] +fn part2(steps: &Vec) -> i64 { + let verticies = get_verticies(steps); + + let mut area: i64 = 0; + + for win in verticies.windows(2) { + area += win[0].y as i64 * win[1].x as i64; + area -= win[0].x as i64 * win[1].y as i64; + } + + (area / 2) + (verticies.len() as i64 / 2) + 1 +} #[cfg(test)] @@ -128,16 +172,16 @@ U 6 (#d2c081)"; #[test] fn part1_example() { - assert_eq!(part1(&parse(EX)), 62); + assert_eq!(part1(&parse_part1(EX)), 62); } #[test] fn part1_example2() { - assert_eq!(part1(&parse(EX_2)), 49); + assert_eq!(part1(&parse_part1(EX_2)), 49); } - // #[test] - // fn part2_example() { - // assert_eq!(part2(&parse(EX)), ""); - // } + #[test] + fn part2_example() { + assert_eq!(part2(&parse_part2(EX)), 952408144115); + } } \ No newline at end of file