--- /dev/null
+use std::iter::Iterator;\r
+use std::collections::HashSet;\r
+\r
+pub fn split_movements(movements: &str) -> Vec<&str> {\r
+ movements.split(',').collect()\r
+}\r
+\r
+pub fn manhattan_distance_from_cross_to_port(wire1: &[&str], wire2: &[&str]) -> i32 {\r
+ fn positions(wire: &[&str]) -> HashSet<(i32, i32)> {\r
+ let (mut x, mut y) = (0, 0);\r
+ let mut pos = HashSet::<(i32, i32)>::new();\r
+ for mov in wire {\r
+ let distance = mov[1..].parse::<i32>().unwrap();\r
+ match mov.chars().nth(0).unwrap() {\r
+ 'U' => { for y2 in y+1 ..= y + distance { pos.insert((x, y2)); } y += distance },\r
+ 'D' => { for y2 in y - distance .. y { pos.insert((x, y2)); } y -= distance },\r
+ 'R' => { for x2 in x+1 ..= x + distance { pos.insert((x2, y)); } x += distance },\r
+ 'L' | _ => { for x2 in x - distance .. x { pos.insert((x2, y)); } x -= distance },\r
+ }\r
+ }\r
+ pos\r
+ }\r
+\r
+ let (positions_wire1, positions_wire2) = (positions(wire1), positions(wire2));\r
+ let cross: HashSet<_> = positions_wire1.intersection(&positions_wire2).collect();\r
+ cross.iter().map(|(x, y)| x.abs() + y.abs()).min().unwrap()\r
+}\r
+\r
+#[cfg(test)]\r
+mod tests {\r
+ use super::*;\r
+\r
+ #[test]\r
+ fn simple_cases() {\r
+ assert_eq!(\r
+ manhattan_distance_from_cross_to_port(\r
+ &split_movements("R8,U5,L5,D3"),\r
+ &split_movements("U7,R6,D4,L4")\r
+ ),\r
+ 6\r
+ );\r
+\r
+ assert_eq!(\r
+ manhattan_distance_from_cross_to_port(\r
+ &split_movements("R75,D30,R83,U83,L12,D49,R71,U7,L72"),\r
+ &split_movements("U62,R66,U55,R34,D71,R55,D58,R83")\r
+ ),\r
+ 159\r
+ );\r
+\r
+ assert_eq!(\r
+ manhattan_distance_from_cross_to_port(\r
+ &split_movements("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51"),\r
+ &split_movements("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")\r
+ ),\r
+ 135\r
+ );\r
+ }\r
+}
\ No newline at end of file
use std::env;
+use std::fs;
use std::time::Instant;
mod day01;
mod day02;
+mod day03;
mod common;
fn day01() -> String {
format!("part1: {}, part2: {}", day02::execute_op_code_with_state_fixed(&mut Vec::from(&code[..])), day02::find_noun_and_verb(&code))
}
+fn day03() -> String {
+ let file_content = fs::read_to_string("data/day03.input").unwrap();
+ let movements: Vec<&str> = file_content.lines().collect();
+ format!(
+ "part1: {}",
+ day03::manhattan_distance_from_cross_to_port(&day03::split_movements(&movements[0]), &day03::split_movements(&movements[1]))
+ )
+}
+
fn do_day(days: &[fn() -> String], day: usize) {
let now = Instant::now();
println!("Result of day {}: {} (time: {} μs)", day, days[day - 1](), now.elapsed().as_micros());
let days: Vec<fn() -> String> = vec!(
day01,
- day02
+ day02,
+ day03
);
let args: Vec<String> = env::args().skip(1).collect();