aoc

Thing1's 2025 aoc
Log | Files | Refs

3b.c (1287B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 /* method
      6 
      7 we know we need 12 bats, so to find the largest number,
      8 we can find the largest digit for each, position. To do this
      9 we can find the difference in length of the input and 12,
     10 then from the first n (the difference in length) digits, pick
     11 the highest one. Then  repeat the function for the other
     12 digits, using the previously chosen digit as an input and
     13 subtracting 1 from the length
     14 */
     15 
     16 char *
     17 findhighest(char *start, char *end) {
     18 	char *highest = start++;
     19 	while (start != end) {
     20 		if (*start > *highest)
     21 			highest = start;
     22 		start++;
     23 	}
     24 	return highest;
     25 }
     26 
     27 char *
     28 finddigit(char *in, int len) {
     29 	int off;
     30 	char *digit;
     31 
     32 	off = strlen(in) - len;
     33 	digit = findhighest(in, in + off + 1);
     34 
     35 	return digit;
     36 }
     37 
     38 char **
     39 finddigits(char *in) {
     40 	static char *digits[12];
     41 
     42 	for (int len = 12; len >= 0; len--) {
     43 		digits[12 - len] = finddigit(in, len);
     44 		in = digits[12 - len] + 1;
     45 	}
     46 
     47 	return digits;
     48 }
     49 
     50 int
     51 main() {
     52 	long long int total = 0;
     53 	char **digits, num[13] = {0};
     54 	char line[256] = {0};
     55 
     56 	while (fgets(line, 256, stdin)) {
     57 		line[strlen(line) - 1] = 0;
     58 		digits = finddigits(line);
     59 		for (int i = 0; i < 12; i++)
     60 			num[i] = *digits[i];
     61 		printf("%s\n", num);
     62 		total += atoll(num);
     63 	}
     64 	printf("%lld\n", total);
     65 }