r/adventofcode • • Dec 06 '15

SOLUTION MEGATHREAD --- Day 6 Solutions ---

--- Day 6: Probably a Fire Hazard ---

Post your solution as a comment. Structure your post like the Day Five thread.

22 Upvotes

171 comments sorted by

View all comments

Show parent comment

1

u/marchelzo Dec 06 '15

I also did it in C, and it was surprisingly similar to yours.

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

static bool lights[1000][1000];

enum {
    ACT_ON,
    ACT_TOGGLE,
    ACT_OFF
};

static int
action(char const *s)
{
    if (!strcmp(s, "turn on "))
        return ACT_ON;
    if (!strcmp(s, "toggle "))
        return ACT_TOGGLE;
    if (!strcmp(s, "turn off "))
        return ACT_OFF;
}

int
main(void)
{
    int x1, x2, y1, y2;
    char act[32];

    while (scanf("%31[^0-9]%d,%d through %d,%d\n", act, &x1, &y1, &x2, &y2) == 5) {
        for (int i = y1; i <= y2; ++i) {
            for (int j = x1; j <= x2; ++j) {
                switch (action(act)) {
                    case ACT_ON:     lights[i][j] = true;  break;
                    case ACT_TOGGLE: --lights[i][j];       break;
                    case ACT_OFF:    lights[i][j] = false; break;
                }
            }
        }
    }

    int on = 0;
    for (int i = 0; i < 1000; ++i) {
        for (int j = 0; j < 1000; ++j) {
            on += lights[i][j];
        }
    }

    printf("%d\n", on);

    return 0;
}