David Marec 8 月之前
父节点
当前提交
e43b9bf1eb
共有 1 个文件被更改,包括 151 次插入0 次删除
  1. 151 0
      dummy/zip.c

+ 151 - 0
dummy/zip.c

@@ -0,0 +1,151 @@
+#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);
+}
+