summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2020/AOC-3/main.c
blob: 6690b5d6ea40c32a772f0a0fbfbccf1852bebefe (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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#if 0
#define PART_1
#else
#define PART_2
#endif

#if 0
#define FILE_PATH "example.txt"
#else
#define FILE_PATH "input.txt"
#endif

int WIDTH  = 0;
int HEIGHT = 0;
#define BOARD_SZ ((WIDTH) * (HEIGHT))

char *board;

void parse()
{
    FILE *fp = fopen(FILE_PATH, "r");
    if(!fp) {
        fprintf(stderr, "ERROR: Could not open file: %s", FILE_PATH);
    }

    char ch;
    int i = 0;
    // calculate size of the board
    while((ch = fgetc(fp)) != EOF)
    {
        if(ch != '\n') {
            i++;
            continue;
        }

        if(WIDTH == 0) WIDTH = i;
    }
    HEIGHT = i / WIDTH;
    board = malloc(BOARD_SZ);

    fseek(fp, 0, SEEK_SET);
    i = 0;
    while((ch = fgetc(fp)) != EOF)
    {
        if(ch == '\n') continue;

        board[i] = ch;
        i++;
    }

    fclose(fp);
}

size_t traverse_map()
{
#ifdef PART_1
    int slope_x[1] = {3};
    int slope_y[1] = {1};
    #define SZ 1
#endif
#ifdef PART_2
    int slope_x[5] = {1, 3, 5, 7, 1};
    int slope_y[5] = {1, 1, 1, 1, 2};
    #define SZ 5
    size_t result = 1;
#endif

    int x, y;
    size_t hit_trees;
    for(int i = 0; i < SZ; i++)
    {
        x = 0;
        y = 0;
        hit_trees = 0;
        while(y != (HEIGHT - 1))
        {
            x += slope_x[i];
            y += slope_y[i];

            if(x >= WIDTH)
                x = x - WIDTH;

            if(board[y * WIDTH + x] == '#')
                hit_trees++;
        }

        #ifdef PART_2
        result *= hit_trees;
        #endif
    }

    #ifdef PART_1
    return hit_trees;
    #endif
    #ifdef PART_2
    return result;

    #endif
}

void print_board()
{
    for(int i = 0; i < BOARD_SZ; i++)
    {
        printf("%c", board[i]);

        if(i % WIDTH == (WIDTH - 1))
            putc('\n', stdout);
    }
}

int main(void)
{
    parse();
    printf("You hit %ld trees", traverse_map());
    free(board);
    return 0;
}