advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

3.c (890B)


      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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#define WIDTH 12

int
main(int argc, char **argv) {
	if (argc < 2) {
		fprintf(stderr, "usage: %s datafile\n", *argv);
		return 1;
	}

	FILE *fd = fopen(argv[1], "r");
	if (fd == NULL) {
		perror(argv[1]);
		return 1;
	}

	int counts[WIDTH] = {0};

	char *buf = NULL;
	size_t buflen = 0;
	int len = 0;
	while (getline(&buf, &buflen, fd) != -1) {
		len++;
		for (int i = 0; i < WIDTH; i++)
			counts[i] += buf[i] == '1' ? 1 : 0;
	}

	uint16_t gamma, epsilon;
	gamma = epsilon = 0;

	for (int i = 0; i < WIDTH; i++) {
		if (counts[i] > len / 2)
			gamma |= 1 << (WIDTH - 1 - i);
		else
			epsilon |= 1 << (WIDTH - 1 - i);
	}

	printf("epsilon: %d\ngamma: %d\n", epsilon, gamma);
	printf("product: %d\n", epsilon * gamma);

	free(buf);

	if (fclose(fd) == EOF) {
		perror("fclose");
		return 1;
	}
	
	return 0;
}