Photolog

Through the Looking-Glass
2010-10-12: Through the Looking-Glass
My radio speaks is binary!
2010-10-10: My radio speaks is binary!
Gigaminx: (present for my birthday)
2010-09-16: Gigaminx: (present for my birthday)
Trini on bike
2010-09-05: Trini on bike
Valporquero
2010-08-28: Valporquero
My new bike!
2010-08-22: My new bike!
Mario and Ana's wedding
2010-08-13: Mario and Ana's wedding
Canyoning in Guara
2010-08-07: Canyoning in Guara
Trini and Mari in Marbella
2010-08-05: Trini and Mari in Marbella
Trini and Chelo in Tabarca
2010-08-03: Trini and Chelo in Tabarca
Valid XHTML 1.1
Log in
Back to list of problems

"Accordian" Patience

127.c

#include <stdio.h>
#include <string.h>

struct pile {
	int n;
	char cards[52][3];
};

int num_piles;
struct pile piles[52];

int
match(int a, int b) {
	if ((piles[a].cards[piles[a].n-1][0] == piles[b].cards[piles[b].n-1][0]) ||
			(piles[a].cards[piles[a].n-1][1] == piles[b].cards[piles[b].n-1][1])) {
		return 1;
	} else {
		return 0;
	}
}

void
move(int orig, int dest) {
	strcpy(piles[dest].cards[piles[dest].n], piles[orig].cards[piles[orig].n-1]);
	piles[dest].n++;
	piles[orig].n--;
	if (!piles[orig].n) {
		memmove(&piles[orig], &piles[orig+1], (num_piles-orig-1)*sizeof(struct pile));
		num_piles--;
	}
}

void
play(void) {
	int i;

again:
	for (i=0; i<num_piles; i++) {
		if (i>=3 && match(i, i-3)) {
			move(i, i-3);
			goto again;
		} else if (i>=1 && match(i, i-1)) {
			move(i, i-1);
			goto again;
		}
	}
}

int
main(void) {
	int i;

	while (1) {
		num_piles = 52;
		for (i=0; i<52; i++) {
			piles[i].n = 1;
			if (scanf(" %s", piles[i].cards[0])!=1 || piles[i].cards[0][0]=='#') {
				return 0;
			}
		}
		play();
		printf("%d pile%s remaining:", num_piles, (num_piles>1 ? "s" : ""));
		for (i=0; i<num_piles; i++) {
			printf(" %d", piles[i].n);
		}
		printf("\n");
	}
}