Skip to content

Instantly share code, notes, and snippets.

@zid

zid/2022-day5.c Secret

Created December 5, 2022 06:47
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/82dac0453e984be7c1fb08ce37a53617 to your computer and use it in GitHub Desktop.
Save zid/82dac0453e984be7c1fb08ce37a53617 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
struct col {
char v;
struct col *next;
};
static struct col *newc(char v)
{
struct col *c = malloc(sizeof *c);
c->v = v;
c->next = NULL;
return c;
}
static void append(struct col **c, char v)
{
struct col *t, **at;
for(at = c; *at; at = &((*at)->next))
;
t = newc(v);
t->next = NULL;
*at = t;
}
static void move(struct col **d, struct col **s)
{
struct col *t;
t = *s;
*s = (*s)->next;
t->next = *d;
*d = t;
}
static void move2(struct col **d, struct col **s, int count)
{
struct col *t, *t2;
int i;
t = *s;
t2 = *s;
for(i = 0; i < count; i++)
*s = (*s)->next;
for(i = 0; i < count-1; i++)
t2 = t2->next;
t2->next = *d;
*d = t;
}
static void dumpcol(struct col *c)
{
struct col *t;
for(t = c; t; t = t->next)
printf("%c -> ", t->v);
puts("NULL");
}
int main(void)
{
char line[1024];
FILE *f;
int r;
f = fopen("day5.txt", "r");
struct col *c[9] = {0};
for(r = 0; r < 8; r++)
{
int i;
if(!fgets(line, 128, f))
break;
for(i = 0; i < 9; i++)
{
char v = line[i*4+1];
putchar(v);
if(v == ' ')
continue;
append(&c[i], v);
}
putchar('\n');
}
for(r = 0; r < 9; r++)
dumpcol(c[r]);
printf("Following commands...\n");
fgets(line, 128, f);
fgets(line, 128, f);
while(1)
{
int count, from, to;
if(!fgets(line, 128, f))
break;
sscanf(line, "move %d from %d to %d\n", &count, &from, &to);
to--;
from--;
printf("\n\nMove %d from %d to %d\n", count, from+1, to+1);
#ifdef P1
for(r = 0; r < count; r++)
move(&c[to], &c[from]);
#else
if(count != 1)
move2(&c[to], &c[from], count);
else
move(&c[to], &c[from]);
#endif
for(r = 0; r < 9; r++)
dumpcol(c[r]);
printf("Moved %d from %d to %d\n", count, from+1, to+1);
}
for(r = 0; r < 8; r++)
{
putchar(c[r]->v);
}
putchar('\n');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment