Skip to content

Instantly share code, notes, and snippets.

@zid

zid/2022-day3.c Secret

Last active December 3, 2022 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zid/c39f4d9dcced30e2cb1a5e5e95716cee to your computer and use it in GitHub Desktop.
Save zid/c39f4d9dcced30e2cb1a5e5e95716cee to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct input
{
size_t len;
char line[1024];
};
static int score(char c)
{
if(c >= 'a' && c <= 'z')
return 1 + c - 'a';
else if(c >= 'A' && c <= 'Z')
return 27 + c - 'A';
else
abort();
}
static int p2(struct input *in)
{
char baga[128] = {0}, bagb[128] = {0}, bagc[128] = {0};
struct input *a, *b, *c;
size_t i;
a = &in[0];
b = &in[1];
c = &in[2];
for(i = 0; i < 128; i++)
{
if(i < a->len)
baga[a->line[i]] = 1;
if(i < b->len)
bagb[b->line[i]] = 1;
if(i < c->len)
bagc[c->line[i]] = 1;
}
for(i = 0; i < 128; i++)
{
if(baga[i] && bagb[i] && bagc[i])
{
return score(i);
}
}
abort();
}
static int p1(struct input *in)
{
char left[128] = {0}, right[128] = {0};
size_t i, h;
h = in->len/2;
printf("Line: len %d, '%s'\n", in->len, in->line);
for(i = 0; i < h; i++)
{
left[in->line[i]] = 1;
right[in->line[i+h]] = 1;
}
for(i = 0; i < 128; i++)
{
if(left[i] && right[i])
return score(i);
}
abort();
}
static int lineget(struct input *in, size_t max, FILE *f)
{
char *p = in->line;
size_t i;
for(i = 0; i < max; i++)
{
int c = fgetc(f);
if(c == EOF)
return 0;
*p = c;
if(*p == '\n' || !*p)
{
*p = 0;
break;
}
p++;
}
if(i == 0 || i == max)
return 0;
in->len = i;
return 1;
}
int main(void)
{
FILE *f;
unsigned long p1sum = 0, p2sum = 0;
f = fopen("day3.txt", "r");
while(1)
{
struct input in[3];
if(!lineget(&in[0], 1024, f))
break;
p1sum += p1(&in[0]);
if(!lineget(&in[1], 1024, f))
break;
p1sum += p1(&in[1]);
if(!lineget(&in[2], 1024, f))
break;
p1sum += p1(&in[2]);
p2sum += p2(in);
}
printf("sum1: %lu, sum2: %lu\n", p1sum, p2sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment