summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-8/main.c
blob: ee36c266128138f44311d72baadb7351c102a3cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#if 0
  #define PART part1
#else
  #define PART part2
#endif

#if 0
  #define FILENAME "sample.txt"
  #define SIDE 5
#else
  #define FILENAME "input.txt"
  #define SIDE 99
#endif

#define MAX(x, y) (((x) > (y)) ? (x) : (y))

int ans = 0;
int table[SIDE][SIDE];

void parse()
{
    FILE *fp = fopen(FILENAME, "r");
    if(!fp) {
        fprintf(stderr, "ERROR: Could not opne file: %s\n", FILENAME);
        exit(1);
    }

    char line[256];
    int col = 0;
    while(fgets(line, sizeof(line), fp))
    {
        assert(col < SIDE);

        for(int i = 0; i < SIDE; i++)
            table[i][col] = line[i] - '0';
        col++;
    }

    fclose(fp);
}

void part1()
{
    ans = (SIDE*4) - 4;

    for(int y = 1; y < (SIDE-1); y++)
        for(int x = 1; x < (SIDE-1); x++)
        {
            int cur = table[x][y];

            // row left
            int rl = 1;
            for(int i = 0; i < x; i++)
                rl &= cur > table[i][y];

            // row right
            int rr = 1;
            for(int i = (x+1); i < SIDE; i++)
                rr &= cur > table[i][y];

            // col up
            int cu = 1;
            for(int i = 0; i < y; i++)
                cu &= cur > table[x][i];

            // col down
            int cd = 1;
            for(int i = (y+1); i < SIDE; i++)
                cd &= cur > table[x][i];

            if(rl || rr || cu || cd) ans++;
        }
}

void part2()
{
    for(int y = 1; y < (SIDE-1); y++)
        for(int x = 1; x < (SIDE-1); x++)
        {
            int cur = table[x][y];

            // row left
            int rl = 0;
            for(int i = (x-1); i >= 0; i--) {
                rl++;
                if(cur <= table[i][y]) break;
            }

            // row right
            int rr = 0;
            for(int i = (x+1); i < SIDE; i++) {
                rr++;
                if(cur <= table[i][y]) break;
            }

            // col up
            int cu = 0;
            for(int i = (y-1); i >= 0; i--) {
                cu++;
                if(cur <= table[x][i]) break;
            }

            // col down
            int cd = 0;
            for(int i = (y+1); i < SIDE; i++) {
                cd++;
                if(cur <= table[x][i]) break;
            }

            ans = MAX(ans, rl * rr * cu * cd);
        }
}

int main(void)
{
    parse();
    PART();
    printf("%d\n", ans);
    return 0;
}