advent-of-code

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

01.c (1124B)


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

void
usage(char *argv0) {
	printf("usage: %s TARGET < input.file\n", argv0);
}

int
main(int argc, char **argv) {
	if (argc < 2) {
		usage(*argv);
		return 1;
	}

	int target = atoi(argv[1]);
	if (target == 0) {
		fprintf(stderr, "error parsing target '%s'\n", argv[1]);
		return 1;
	}

	/* buffer for each line */
	char buf[100] = {'\0'};

	size_t nums_len = 200;
	int *nums = malloc(sizeof(int) * nums_len);
	if (nums == NULL) {
		perror("malloc");
		return 1;
	}
	int *n = nums;

	while (fgets(buf, 100, stdin) != NULL) {
		*n++ = atoi(buf);
		size_t offset = n - nums;
		if (offset > nums_len) {
			nums_len += 10;
			int *tmp = realloc(nums, sizeof(int) * nums_len);
			if (tmp == NULL) {
				perror("realloc");
				goto error_free_nums;
			}

			nums = tmp;
			n = nums + offset;
		}
	}

	for (size_t i = 0; i < nums_len; i++) {
		for (size_t j = i + 1; j < nums_len; j++) {
			if (nums[i] + nums[j] == target) {
				printf("%d * %d = %d\n", nums[i], nums[j], nums[i] * nums[j]);
				goto end;
			}
		}
	}
end:
	free(nums);
	return 0;
error_free_nums:
	free(nums);
	return 1;
}