Day 12: Garden Groups
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
You are viewing a single thread.
View all comments 4 points
C
No big trouble today, just a bit of careful debugging of my part 2 logic for which I was greatly helped by some Redditor’s testcase 🙏
Happy to have gotten it all in the single flood fill function without any extra passes.
Code
#include "common.h"
#define GZ 144
static char g[GZ][GZ];
static char seen[GZ][GZ];
static void
count(char c, int x, int y, int *area, int *perim, int *sides)
{
if (g[y][x] != c) { (*perim)++; return; }
if (seen[y][x]) return;
*area += 1;
seen[y][x] = 1;
/* count start of top/left edges, end of bottom/right edges */
*sides += g[y-1][x]!=c && ((g[y-1][x-1]==c) || (g[y][x-1]!=c));
*sides += g[y+1][x]!=c && ((g[y+1][x+1]==c) || (g[y][x+1]!=c));
*sides += g[y][x-1]!=c && ((g[y-1][x-1]==c) || (g[y-1][x]!=c));
*sides += g[y][x+1]!=c && ((g[y+1][x+1]==c) || (g[y+1][x]!=c));
count(c, x, y-1, area, perim, sides);
count(c, x, y+1, area, perim, sides);
count(c, x-1, y, area, perim, sides);
count(c, x+1, y, area, perim, sides);
}
int
main(int argc, char **argv)
{
int p1=0,p2=0, x,y, area, perim, sides;
if (argc > 1)
DISCARD(freopen(argv[1], "r", stdin));
for (y=1; fgets(g[y]+1, GZ-2, stdin); y++)
assert(y+1 < GZ);
for (y=1; y<GZ-1; y++)
for (x=1; x<GZ-1; x++)
if (isalpha(g[y][x]) && !seen[y][x]) {
area = perim = sides = 0;
count(g[y][x], x, y, &area, &perim, &sides);
p1 += area * perim;
p2 += area * sides;
}
printf("12: %d %d\n", p1, p2);
}
2 points
3 points