summaryrefslogtreecommitdiff
path: root/2022/day05/main2.c
diff options
context:
space:
mode:
Diffstat (limited to '2022/day05/main2.c')
-rw-r--r--2022/day05/main2.c129
1 files changed, 129 insertions, 0 deletions
diff --git a/2022/day05/main2.c b/2022/day05/main2.c
new file mode 100644
index 0000000..f7fe805
--- /dev/null
+++ b/2022/day05/main2.c
@@ -0,0 +1,129 @@
+
+#include <stdio.h>
+#include <stdlib.h>
+
+struct StackItem_;
+
+typedef struct StackItem_ {
+ char value;
+ struct StackItem_ *next, *prev;
+} StackItem;
+
+typedef struct Stack_ {
+ StackItem *top, *bottom;
+} Stack;
+
+void push_top(Stack *stack, StackItem *item) {
+ if (stack->top)
+ {
+ StackItem* old = stack->top;
+ old->next = item;
+ item->prev = old;
+ }
+ if (!stack->top) stack->bottom = item;
+ stack->top = item;
+}
+
+void push_back(Stack *stack, StackItem *item) {
+ if (stack->bottom)
+ {
+ StackItem* old = stack->bottom;
+ old->prev = item;
+ item->next = old;
+ }
+ if (!stack->bottom) stack->top = item;
+ stack->bottom = item;
+}
+
+StackItem* pop_top(Stack *stack) {
+ StackItem* old = stack->top;
+ stack->top = old->prev;
+ if (old->prev != 0)
+ {
+ stack->top->next = 0;
+ }
+ old->next = old->prev = 0;
+
+ return old;
+}
+
+StackItem* pop_back(Stack *stack) {
+ StackItem* old = stack->bottom;
+ stack->bottom = old->next;
+ stack->bottom->prev = 0;
+ old->next = old->prev = 0;
+
+ return old;
+}
+
+void printCargo(Stack *cargo, size_t len)
+{
+ for (int i = 0; i < len; i++)
+ {
+ for ( StackItem *e = cargo[i].bottom; e != 0; e = e->next )
+ {
+ printf("%c", e->value);
+ }
+ printf("\n");
+ }
+}
+
+int main()
+{
+ char *line = 0;
+ size_t len;
+ Stack *cargo;
+ size_t cargos;
+ ssize_t nread;
+
+ int amount, from, to;
+
+ Stack *temp = malloc(sizeof(Stack));
+
+ while ((nread = getline(&line, &len, stdin)) != 0)
+ {
+ if ( line[1] == '1' ) continue;
+ if ( line[0] == '\n' ) break;
+ if ( !cargo ) {
+ cargos = (nread+1)/4;
+ cargo = (Stack*)malloc( sizeof(Stack) * cargos );
+ }
+
+ for (int i = 0; i < cargos; i++ ) {
+ char load = line[i*4+1];
+ if ( load != ' ' ) {
+ StackItem *box = malloc(sizeof(StackItem));
+ box->value = line[i*4+1];
+ box->next = box->prev = 0;
+ push_back(&cargo[i], box);
+ }
+ }
+ }
+
+ printCargo(cargo, cargos);
+ printf("---------------\n");
+
+ while (scanf("move %d from %d to %d\n", &amount, &from, &to) != EOF)
+ {
+ printf( "%d %d %d\n", amount, from, to );
+ for (int i = 0; i < amount; i++)
+ {
+ StackItem *item = pop_top(&cargo[from-1]);
+ push_top(temp, item);
+ }
+ for (int i = 0; i < amount; i++)
+ {
+ StackItem *item = pop_top(temp);
+ push_top(&cargo[to-1], item);
+
+ printCargo(cargo, cargos);
+ printf("---------------\n");
+ }
+ }
+
+ for ( int i = 0; i < cargos; i++ )
+ {
+ printf( "%c", cargo[i].top->value );
+ }
+ printf("\n");
+}