Skip to content

Instantly share code, notes, and snippets.

@zid

zid/2021-day3.c Secret

Created December 3, 2021 13:10
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/b260141c6f1ac690ce110072cea998b3 to your computer and use it in GitHub Desktop.
Save zid/b260141c6f1ac690ce110072cea998b3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
static unsigned int lines[1000];
static unsigned int lastmatch;
static int cb(int mask, int len, int inv)
{
int i, c = 0;
for(i = 0; i < 1000; i++)
{
if(!inv)
{
if((lines[i] >> 12-len) == mask)
{
c++;
lastmatch = lines[i];
}
}
else
{
if(((~lines[i])&0xFFF) >> 12-len == mask)
{
c++;
lastmatch = lines[i];
}
}
}
return c;
}
static void param(int inv)
{
int len = 1, mask = 1, count = 1000;
while(len <= 12)
{
int t, r;
t = cb(mask, len, inv);
if(t == 1)
break;
if(!inv)
r = (t >= count/2);
else
r = (t <= count/2);
if(r)
{
mask <<= 1;
mask |= 1;
count = t;
}
else
{
mask ^= 1;
mask <<= 1;
mask |= 1;
count = count-t;
}
len++;
}
printf("lastmatch = %u\n", mask, lastmatch);
}
int main(void)
{
FILE *f;
char line[128];
int i = 0, mask = 0;
int len = 1;
int count = 1000;
f = fopen("day3.txt", "r");
while(1)
{
unsigned int n;
if(!fgets(line, 128, f))
goto out;
n = strtoul(line, NULL, 2);
lines[i++] = n;
}
out:
param(0);
param(1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment