Day 3: Lobby

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 3 points 9 months ago* (last edited 9 months ago) (1 child)

c

#include "aoc.h"
#include <stdio.h>
#include <string.h>

constexpr usize LINE_BUFSZ = (1 << 7);
constexpr u64 TEN = 10;
constexpr u64 TWELVE = 12;

static void
joltage(strc line, u64* total, usize on) {
  usize len = strlen(line);
  usize off = len - on;
  usize slen = 0;
  c8 stack[LINE_BUFSZ] = {};
  for (usize i = 0; i < len; i++) {
    while (slen > 0 && off > 0 && stack[slen - 1] < line[i]) {
      slen--;
      off--;
    }
    stack[slen++] = line[i];
  }
  u64 jltg = 0;
  for (usize i = 0; i < on; i++) {
    jltg = (jltg * TEN) + (u64)(stack[i] - '0');
  }
  *total += jltg;
}

static void
solve(u64 on) {
  FILE* input = fopen("input", "r");
  c8 line[LINE_BUFSZ] = {};
  u64 total = 0;
  while (fgets(line, sizeof(line), input)) {
    line[strcspn(line, "\n")] = 0;
    joltage(line, &total, on);
  }
  fclose(input);
  printf("%lu\n", total);
}

i32
main(void) {
  solve(2);
  solve(TWELVE);
}
  • source
  • hideshow 1 child comment