129 lines
2.6 KiB
C
129 lines
2.6 KiB
C
#include "lib.h"
|
|
|
|
#define DBG 0
|
|
|
|
static
|
|
unsigned char input[] = {
|
|
#embed "day3_input.txt"
|
|
};
|
|
|
|
static
|
|
unsigned char test[] = {
|
|
#embed "day3_test.txt"
|
|
};
|
|
|
|
|
|
static
|
|
unsigned long do_part1(size_t file_len, unsigned char file[file_len]) {
|
|
unsigned long result = 0;
|
|
unsigned char *s = file;
|
|
|
|
do {
|
|
unsigned char n0 = 0, n1 = 0;
|
|
unsigned char *n0p = NULL;
|
|
do {
|
|
if (s[0] > n0) {
|
|
n0 = s[0];
|
|
n0p = s;
|
|
}
|
|
s++;
|
|
} while (s[1] != '\n');
|
|
s = n0p+1;
|
|
do {
|
|
if (s[0] > n1) {
|
|
n1 = s[0];
|
|
}
|
|
s++;
|
|
} while (s[0] != '\n');
|
|
s++;
|
|
unsigned n = (n0 - '0') * 10 + (n1 - '0');
|
|
result += n;
|
|
} while(s < &file[file_len]);
|
|
|
|
return result;
|
|
}
|
|
|
|
static
|
|
unsigned long do_part2(size_t file_len, unsigned char file[file_len]) {
|
|
unsigned long result = 0;
|
|
unsigned char *s = file;
|
|
|
|
do {
|
|
// for some reason this crashes
|
|
// but works fine under blink so.
|
|
// whatever
|
|
unsigned char n[12] = { };
|
|
unsigned char *np[12] = { };
|
|
for (int i = 0; i < 12; i++) {
|
|
do {
|
|
if (s[0] > n[i]) {
|
|
n[i] = s[0];
|
|
np[i] = s;
|
|
}
|
|
s++;
|
|
} while (s[11-i] != '\n');
|
|
s = np[i]+1;
|
|
}
|
|
unsigned long v = 0;
|
|
for (int i = 0; i < 12; i++) {
|
|
v = v * 10 + (n[i] - '0');
|
|
}
|
|
#if DBG
|
|
print("got ");
|
|
printd(v);
|
|
print("\n");
|
|
#endif
|
|
result += v;
|
|
while (*s != '\n') s++;
|
|
s++;
|
|
} while(s < &file[file_len]);
|
|
|
|
return result;
|
|
}
|
|
|
|
#define RUN_TEST1 1
|
|
#define RUN_PART1 1
|
|
#define RUN_TEST2 1
|
|
#define RUN_PART2 1
|
|
|
|
#define TEST1_EXPECT 357
|
|
#define TEST2_EXPECT 3121910778619
|
|
|
|
void _start() {
|
|
#if RUN_TEST1
|
|
print("PART 1 TEST: ");
|
|
if (unsigned long v = do_part1(countof(test), test); v != TEST1_EXPECT) {
|
|
print("FAILED (got ");
|
|
printd(v);
|
|
print(", expected " xstr(TEST1_EXPECT) ")\n");
|
|
} else {
|
|
print("PASSED\n");
|
|
}
|
|
#endif
|
|
|
|
#if RUN_PART1
|
|
print("PART 1 RESULT: ");
|
|
printd(do_part1(countof(input), input));
|
|
print("\n");
|
|
#endif
|
|
|
|
#if RUN_TEST2
|
|
print("PART 2 TEST: ");
|
|
if (unsigned long v = do_part2(countof(test), test); v != TEST2_EXPECT) {
|
|
print("FAILED (got ");
|
|
printd(v);
|
|
print(", expected " xstr(TEST2_EXPECT) ")\n");
|
|
} else {
|
|
print("PASSED\n");
|
|
}
|
|
#endif
|
|
|
|
#if RUN_PART2
|
|
print("PART 2 RESULT: ");
|
|
printd(do_part2(countof(input), input));
|
|
print("\n");
|
|
#endif
|
|
|
|
syscall(SYS_exit_group, 0);
|
|
}
|