Source

Day 1 - Advent of Code 2018

Description

Part 1: return the sum of all the input values.

Part 2: return the first cumulative sum that has already been seen, reprocessing the input values repeatedly if necessary.

My solution

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
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char * filename = "input.txt";
    FILE * file = fopen(filename, "r");
    int changes[964];

    // You need enough memory here. I guessed.
    int seen[1000000];

    int freq = 0;
    seen[0] = 0;
    int i = 0;
    int first_twice;
    _Bool first_twice_found = 0;

    char line[10];

    // Collect all the values from input and put them in `changes`.
    // Compute the frequency meanwhile, and check to see if any
    // frequency value repeats.
    while (fgets(line, sizeof(line), file) != NULL) {
        int n = atoi(line);
        changes[i] = n;
        freq += n;
        for (int k = 0; k <= i; k++) {
            if (seen[k] == freq) {
                first_twice = freq;
                first_twice_found = 1;
                break;
            }
        }
        if (!first_twice_found) seen[++i] = freq;
    }

    printf("Solution to part 1: %d\n", freq);

    // If we've reach this point, it's because a frequency value
    // has not yet repeated. Re-apply the changes until it does.
    while (!first_twice_found) {
        for (int j = 0; j < 965; j++) {
            freq += changes[j];
            for (int k = 0; k <= i; k++) {
                if (seen[k] == freq) {
                    first_twice = freq;
                    first_twice_found = 1;
                    break;
                }
            }
            if (first_twice_found) break;
            seen[++i] = freq;
        }
    }

    printf("Solution to part 2: %d\n", first_twice);

    fclose(file);
    return 0;
}