Files
Dobos Ádám 408e422b7b Day5
2022-12-10 18:18:29 +01:00

94 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 64
#define STACK_SIZE 64
typedef struct stackStruct {
char s[STACK_SIZE];
char *h;
} stack;
void cp(char*, stack*);
char pop(stack*);
void push(stack*, char);
void move_n(stack*, int, int, int);
int main() {
char buf[BUFFER_SIZE], *p, c;
memset(buf, 0, BUFFER_SIZE);
p = buf;
int first = 1, numofstacks, counter = 0;
int moveCount, moveFrom, moveTo;
stack *stacks;
while ((c = getchar()) != EOF) {
*p++ = c;
if (c == '\n') {
if (first) {
first = 0;
sscanf(buf, "%i", &numofstacks);
stacks = (stack*)malloc(numofstacks * sizeof(stack));
for (int i = 0; i < numofstacks; i++) {
memset(stacks[i].s, 0, STACK_SIZE);
stacks[i].h = stacks[i].s;
}
} else if (counter < numofstacks) {
cp(buf, &stacks[counter]);
counter++;
} else {
sscanf(buf, "move %i from %i to %i", &moveCount, &moveFrom, &moveTo);
// First part
//for (int i = 0; i < moveCount; i++) {
// push(&stacks[moveTo - 1], pop(&stacks[moveFrom -1]));
//}
//
// Second part
move_n(stacks, moveCount, moveFrom-1, moveTo-1);
}
memset(buf, 0, BUFFER_SIZE);
p = buf;
}
}
printf("Stacks:\n");
for (int i = 0; i < numofstacks; i++) {
printf("%s\n", stacks[i].s);
}
printf("\nTop:\n");
for (int i = 0; i < numofstacks; i++) {
printf("%c", *(stacks[i].h - 1));
}
printf("\n");
free(stacks);
}
void cp(char* p, stack* st) {
char *q = st->s;
while((*q++ = *p++) != '\n') {}
*(--q) = 0;
st->h = q;
}
char pop(stack* st) {
char c = *(--st->h);
*st->h = 0;
return c;
}
void push(stack* st, char c) {
*st->h++ = c;
}
void move_n(stack* stacks, int count, int from, int to) {
for (int i = count; i > 0; i--) {
*stacks[to].h++ = *(stacks[from].h - i);
*(stacks[from].h - i) = 0;
}
stacks[from].h -= count;
}