advent-of-code

Solutions for Advent of Code.
git clone git://git.amin.space/advent-of-code.git
Log | Files | Refs | LICENSE

day01_01.c (2039B)


      1 #if 0
      2 # Self-building c file. Invoke like: `./file.c`
      3 outdir=out
      4 input=$(basename "$0")
      5 output="$outdir"/$(basename "$0" .c)
      6 if [ "$input" -nt "$output" ];
      7 then
      8     mkdir --parents "$outdir" || exit
      9     echo "Building ${output}." || exit
     10     clang -std=c11 -Wall -Wextra -pedantic -Wno-unused-function -I../../amlibs/ "$input" -o "$output" || exit
     11 fi
     12 if [ "$1" = "-r" ];
     13 then
     14     ./"$output" "$@"
     15 fi
     16 exit
     17 #endif
     18 
     19 #include <inttypes.h>
     20 #include <errno.h>
     21 #include <stdio.h>
     22 #include <stdlib.h>
     23 _Noreturn void assert_fail(const char *expr, const char *file, int line, const char *func) {
     24     fprintf(stderr, "%s:%d: %s: Assertion failed: '%s'\n", file, line, func, expr);
     25     abort();
     26 }
     27 
     28 #define AM_ENABLE_ASSERT 1
     29 #define AM_ASSERT_FAIL(expr, file, line, func) assert_fail(expr, file, line, func)
     30 #include "am_base.h"
     31 #include "am_memory.h"
     32 #include "am_list.h"
     33 #include "am_string.h"
     34 
     35 Str open_file(MemArena *arena, char *path) {
     36     FILE *f = fopen(path, "r");
     37     assert(f);
     38 
     39     s32 error = fseek(f, 0L, SEEK_END);
     40     assert(!error);
     41 
     42     s64 size = ftell(f);
     43     assert(size >= 0);
     44     rewind(f);
     45 
     46     u8 *buf = am_mem_arena_push(arena, size);
     47     assert(buf);
     48 
     49     size_t items_read = fread(buf, 1, size, f);
     50     assert(items_read == (size_t)size);
     51 
     52     error = fclose(f);
     53     assert(!error);
     54 
     55     return am_str(buf, size);
     56 }
     57 
     58 int main(void) {
     59     MemArena a = am_mem_arena_create(am_mem_base_allocator_malloc());
     60     Str input = open_file(&a, "day01_input.txt");
     61     StrList lines = am_str_split(&a, input, (u8 *)"\n", 1);
     62     u64 increase_count = 0;
     63     u64 previous_number = UINT64_MAX;
     64     for (StrListNode *line = lines.first; line; line = line->next) {
     65         u64 number = 0;
     66         for (usz i = 0; i < line->s.size; i++) {
     67             u64 digit = line->s.str[i] - '0';
     68             number = (number * 10) + digit;
     69         }
     70         increase_count += (number > previous_number);
     71         previous_number = number;
     72     }
     73     printf("Increase Count: %" PRIu64 "\n", increase_count);
     74     am_mem_arena_release(&a);
     75     return 0;
     76 }