| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc_np.h>
- #include <string.h>
- typedef struct {
- size_t len;
- char *items[10];
- } truc_array;
- enum dirs {
- R, /* right */
- L, /* left */
- U, /* up */
- D /* down */
- };
- static __attribute((malloc)) __attribute__((nonnull)) char *get_it(truc_array const *src)
- {
- char *r = mallocx(src->len, MALLOCX_ZERO);
- size_t n = 0;
- enum dirs dir = R;
- int x = 0, y = 0;
- while (src->len && (n < src->len)) {
- char c;
- while((c = src->items[y][x]) != ' ') {
- /* store */
- if (c != '*')
- r[n++] = c;
- if (n == src->len)
- break;
- /* test next one */
- int tx = x;
- int ty = y;
- switch (dir) {
- case R:
- tx++;
- break;
- case L:
- tx--;
- break;
- case U:
- ty--;
- break;
- case D:
- ty++;
- break;
- default:
- fprintf(stderr, "Bug!\n");
- break;
- }
- /* ouch */
- if (tx > 14 || tx < 0 || ty <0 || ty > 9)
- break;
- if ((c = src->items[ty][tx]) == ' ')
- break;
- /* valid next */
- x = tx;
- y = ty;
- }
- switch (dir) {
- char c_up, c_down, c_left, c_right;
- case R:
- case L:
- /* cover up and down */
- c_up = ' ';
- c_down = ' ';
- if (y > 1)
- c_up = src->items[y - 1][x];
- if (y < 9)
- c_down = src->items[y + 1][x];
- if (c_up != ' ') {
- y = y - 1;
- dir = U;
- }
- else if (c_down != ' ') {
- y = y + 1;
- dir = D;
- }
- else
- return r;
- break;
- case U:
- case D:
- /* cover left and right */
- c_left = ' ';
- c_right = ' ';
- if (x > 1)
- c_left = src->items[y][x - 1];
- if (y < 14)
- c_right = src->items[y][x + 1];
- if (c_left != ' ') {
- x = x - 1;
- dir = L;
- }
- else if (c_right != ' ') {
- x = x + 1;
- dir = R;
- } else
- return r;
- break;
- }
- }
- return r;
- }
- static void print_it(truc_array src)
- {
- printf("+---------------+\n");
- for (size_t j= 0; j < 10;) {
- printf("|%s|\n", src.items[j++]);
- }
- printf("+---------------+\n");
- }
- int main(int argc, char *argv[])
- {
- truc_array a= {128, };
- char *r = NULL;
- /* 012345789ABCDEF */
- a.items[0] = "*01** ";
- a.items[1] = "edcBA ";
- a.items[2] = "* * X ";
- a.items[3] = "* ! * ";
- a.items[4] = "****F** ";
- a.items[5] = " * *H* ";
- a.items[6] = " *G** * ";
- a.items[7] = " X I ";
- a.items[8] = " X **J**** ";
- a.items[9] = "X Z ";
- print_it(a);
- puts("");
- r = get_it(&a);
- printf("[ %s ]\n", r);
- dallocx(r, 0);
- }
|