1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
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<Line>) -> 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<String> = 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<Line> = Vec::new();
let mut lines2: Vec<Line> = 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);
}
|