-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday5.c3
113 lines (100 loc) · 2.55 KB
/
day5.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
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
108
109
110
111
112
import std::io;
import std::time;
import std::collections;
import std::sort;
//const int ORDER_LEN = 21;
//const String FILE = "test.txt";
const int ORDER_LEN = 1176;
const String FILE = "input.txt";
int[2][ORDER_LEN] rules;
fn List(<String>)! page_updates()
{
File f = file::open(FILE, "r")!;
defer (void)f.close();
usz row = 0;
List(<String>) page_updates;
while (try line = io::treadline(&f)) {
String[] rule = line.tsplit("|");
if (rule.len == 2) {
rules[row][0] = rule[0].to_int()!;
rules[row][1] = rule[1].to_int()!;
row++;
} else if (line.len > 1) {
page_updates.push(line);
}
}
return page_updates;
}
fn int! List(<String>).count_mid(self, List(<String>)* unordered)
{
int total = 0;
foreach(page: self) {
String[] split = page.tsplit(",");
bool ordered = true;
for (int i = 0; i< split.len; i++) {
int key = split[i].to_int()!;
for (int j = i + 1; j< split.len; j++) {
int value = split[j].to_int()!;
if (!rules.has(key, value)) {
ordered = false;
}
}
}
if (ordered) {
int middle = split[(split.len-1) /2].to_int()!;
total += middle;
} else {
unordered.push(page);
}
}
return total;
}
fn bool int[2][ORDER_LEN].has(self, int key, int value)
{
for(int dy = 0; dy < ORDER_LEN; dy++) {
if (key == self[dy][0] && value == self[dy][1]) {
return true;
}
}
return false;
}
fn int cmp(void* a, void* b)
{
int l = *(int*)a;
int r = *(int*)b;
if (rules.has(l, r)) return 1;
if (rules.has(r, l)) return -1;
return 0;
}
fn long! part1()
{
int total = 0;
List(<String>) pages = page_updates()!;
List(<String>) unordered;
total += pages.count_mid(&unordered)!;
return total;
}
fn long! part2()
{
int total = 0;
List(<String>) pages = page_updates()!;
List(<String>) unordered;
pages.count_mid(&unordered)!;
foreach(page: unordered) {
String[] split = page.tsplit(",");
List(<int>) sorted;
foreach(i, s: split) {
sorted.push(s.to_int()!);
}
sort::quicksort(sorted, &cmp);
int middle = sorted[(sorted.len()) / 2];
total += middle;
}
return total;
}
fn void main()
{
Clock c = clock::now();
io::printfn("- Part1: %d - %s", part1()!!, c.mark());
io::printfn("- Part2: %d - %s", part2()!!, c.mark());
}