From aa9724dfbf5895c8d2f5b8d605a76a3517a2021b Mon Sep 17 00:00:00 2001 From: Mart Lubbers Date: Fri, 17 Dec 2021 09:38:53 +0100 Subject: [PATCH] cleanup part one and do part two --- 17a.c | 31 ++++++------------------------- 17b.c | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 25 deletions(-) create mode 100644 17b.c diff --git a/17a.c b/17a.c index 2140026..903978e 100644 --- a/17a.c +++ b/17a.c @@ -1,21 +1,17 @@ #include -#include #include -#include bool is_in(int dx, int dy, int x1, int x2, int y1, int y2, int *maxy) { int x = 0, y = 0, my = 0; - while (y >= y2 && x <= x2) { + while (y >= y1 && x <= x2) { x+=dx; y+=dy; + my = y > my ? y : my; dx = dx == 0 ? 0 : dx-1; dy--; - if (y > my) - my = y; - if (x >= x1 && x <= x2 && y >= y1 && y <= y2) { - if (my > *maxy) - *maxy = my; + if (x >= x1 && x <= x2 && y >= y1 && y <= y2) { + *maxy = my > *maxy ? my : *maxy; return true; } } @@ -24,23 +20,8 @@ bool is_in(int dx, int dy, int x1, int x2, int y1, int y2, int *maxy) int main() { - size_t len; - char *buf = NULL; - if (getline(&buf, &len, stdin) == -1) - return 1; - printf("%s", buf); - - while (*buf++ != '='); - - int x1 = strtol(buf, &buf, 10); - buf+=strlen(".."); - int x2 = strtol(buf, &buf, 10); - buf+=strlen(", y="); - int y1 = strtol(buf, &buf, 10); - buf+=strlen(".."); - int y2 = strtol(buf, &buf, 10); - - int maxy = 0; + int x1, x2, y1, y2, maxy = 0; + scanf("target area: x=%d..%d, y=%d..%d\n", &x1, &x2, &y1, &y2); for (int dy = x2; dy >= 0; dy--) for (int dx = 1; dx <= x2; dx++) if (is_in(dx, dy, x1, x2, y1, y2, &maxy)) diff --git a/17b.c b/17b.c new file mode 100644 index 0000000..a90c27f --- /dev/null +++ b/17b.c @@ -0,0 +1,27 @@ +#include +#include + +bool is_in(int dx, int dy, int x1, int x2, int y1, int y2) +{ + int x = 0, y = 0; + while (y >= y1 && x <= x2) { + x+=dx; + y+=dy; + dx = dx == 0 ? 0 : dx-1; + dy--; + if (x >= x1 && x <= x2 && y >= y1 && y <= y2) + return true; + } + return false; +} + +int main() +{ + int x1, x2, y1, y2, n = 0; + scanf("target area: x=%d..%d, y=%d..%d\n", &x1, &x2, &y1, &y2); + for (int dy = x2; dy >= y1; dy--) + for (int dx = 0; dx <= x2; dx++) + if (is_in(dx, dy, x1, x2, y1, y2)) + n++; + printf("%d\n", n); +} -- 2.20.1