use num::abs; use std::env; use std::fs::File; use std::io::Read; #[derive(Debug, PartialEq, Clone)] struct Line { dir: char, len: usize, } fn hex_to_line(hex: &str) -> Line { let len = hex[2..7] .chars() .fold(0, |x, y| x * 16 + y.to_digit(16).unwrap()); let dir = match hex.chars().nth(7).unwrap() { '0' => 'R', '1' => 'D', '2' => 'L', '3' => 'U', _ => panic!(), }; return Line { dir: dir, len: len as usize, }; } fn lines_to_coords(path: &Vec) -> Vec<(i64, i64)> { let mut coords: Vec<(i64, i64)> = Vec::new(); coords.push((0, 0)); let mut x: i64 = 0; let mut y: i64 = 0; for l in path { match l.dir { 'R' => { x += l.len as i64; coords.push((x, y)); } 'L' => { x -= l.len as i64; coords.push((x, y)); } 'U' => { y -= l.len as i64; coords.push((x, y)); } 'D' => { y += l.len as i64; coords.push((x, y)); } _ => panic!(), } } coords.push((0, 0)); coords } fn shoelace(coords: &Vec<(i64, i64)>) -> i64 { let mut area: i64 = 0; let mut perimeter: i64 = 0; for ((x0, y0), (x1, y1)) in coords.iter().zip(coords.iter().skip(1)) { // area += (y0+y1) * (x0 - x1); area += x0 * y1 - x1 * y0; perimeter += abs(y1 - y0) + abs(x1 - x0); } area / 2 + perimeter / 2 + 1 } fn main() { let args: Vec = env::args().collect(); let filename = if args.len() == 1 { "in/".to_owned() + args[0].split('/').last().unwrap() + ".pzl" } else { args[1].clone() }; let mut f = File::open(filename).expect("cannot open file"); let mut content = String::new(); f.read_to_string(&mut content).expect("cannot read file"); let lines = content.trim_end().split('\n'); let mut lines1: Vec = Vec::new(); let mut lines2: Vec = Vec::new(); for line in lines { let (a, ar) = line.split_once(' ').unwrap(); let (b, hex) = ar.split_once(' ').unwrap(); let a = a.chars().next().unwrap(); let b = b.parse().unwrap(); // let c:u32 = c[2..c.len()-1].parse().unwrap(); lines1.push(Line { dir: a, len: b }); lines2.push(hex_to_line(hex)); } let coords1 = lines_to_coords(&lines1); let coords2 = lines_to_coords(&lines2); let res1 = shoelace(&coords1); let res2 = shoelace(&coords2); println!("res1: {}", res1); println!("res2: {}", res2); assert_eq!(res1, 31171); assert_eq!(res2, 131431655002266); }