aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

7b.c (1109B)


      1 #include <inttypes.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 
      6 #define N 100000
      7 
      8 int value[255] = {
      9 	['2'] = 2, ['3'] = 3, ['4'] = 4, ['5'] = 5,
     10 	['6'] = 6, ['7'] = 7, ['8'] = 8, ['9'] = 9,
     11 	['T'] = 10, ['J'] = 1, ['Q'] = 12, ['K'] = 13, ['A'] = 14
     12 };
     13 
     14 typedef struct { char c[5]; int64_t b; } hand_t;
     15 
     16 int strength(hand_t h) {
     17 	int i, c2, c1, s, x[15];
     18 
     19 	memset(x, 0, 15 * sizeof(int));
     20 	for (i = 0, s = 0; i < 5; i++) {
     21 		s = s * 15 + value[(int)h.c[i]];
     22 		x[value[(int)h.c[i]]]++;
     23 	}
     24 	for (i = 2, c1 = 0, c2 = 0; i < 15; i++) {
     25 		if (c1 < x[i]) {
     26 			c2 = c1;
     27 			c1 = x[i];
     28 		} else if (c2 < x[i]) c2 = x[i];
     29 	}
     30 
     31 	return ((c1+x[1])*5 + c2) * 759375 + s;
     32 }
     33 
     34 int compare(const void *h1, const void *h2) {
     35 	return strength(*(hand_t *)h1) - strength(*(hand_t *)h2);
     36 }
     37 
     38 int main() {
     39 	char line[N];
     40 	hand_t hand[N];
     41 	int64_t i, n, p;
     42 
     43 	for (n = 0; fgets(line, N, stdin) != NULL; n++) {
     44 		memcpy(hand[n].c, line, 5);
     45 		hand[n].b = atoll(line+6);
     46 	}
     47 
     48 	qsort(hand, n, sizeof(hand_t), &compare);
     49 
     50 	for (i = 0, p = 0; i < n; i++)
     51 		p += hand[i].b * (i+1);
     52 
     53 	printf("%" PRId64 "\n", p);
     54 	return 0;
     55 }