-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.c3
75 lines (67 loc) · 1.35 KB
/
day1.c3
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
import std::io;
import std::math;
import std::collections;
struct Pair {
usz left;
usz right;
}
fn Pair into_day1(String line) {
String[] split = line.tsplit(" ");
return Pair {
split[0].to_long()!!,
split[1].to_long()!!
};
}
fn void! main()
{
File f = file::open("test.txt", "rb")!!;
defer (void) f.close();
List(<Pair>) pairs;
while (try line = io::treadline(&f))
{
pairs.push(into_day1(line));
}
part1(pairs);
part2(pairs);
}
fn void part1(List(<Pair>) pairs)
{
PriorityQueue(<long>) left, right;
long sum = 0;
left.temp_init();
right.temp_init();
foreach(pair : pairs) {
left.push(pair.left);
right.push(pair.right);
}
while (left.len()) {
long diff = math::abs(left.pop() - right.pop())!!;
sum += diff;
}
left.free();
right.free();
io::printfn("part1: %d" , sum);
}
fn void part2(List(<Pair>) pairs)
{
List(<usz>) right;
foreach(pair : pairs) {
right.push(pair.right);
}
usz sum = 0;
foreach (pair : pairs) {
sum += pair.left * count(pair.left, right);
}
right.free();
io::printfn("part2: %d", sum);
}
fn usz count(usz num, List(<usz>) list)
{
usz sum = 0;
foreach (l : list) {
if (l == num) {
sum++;
}
}
return sum;
}