summaryrefslogtreecommitdiff
path: root/10/part2.c
blob: 5053ae7f9bc9f02de61d2db6786003957f0a6e0e (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
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define MAX_INPUT_LEN 128

void insert_value_sorted(int *list, size_t *size, int value)
{
    long long low = 0, high = *size;
    while (low < high) {
        int m = low + (high - low) / 2;
        if (list[m] == value) {
            /* Name already exists,
                return pointer to the already existsing string and free the new one.
            */
            return;
        }
        else if (list[m] < value) {
            low = m + 1;
        }
        else {
            high = m;
        }
    }

    for (long long i = *size - 1; i >= low; i--) {
        list[i + 1] = list[i];
    }

    (*size)++;
    list[low] = value;
}

size_t bags_count(const char *filename)
{
    FILE *file = fopen(filename, "r");

    // Include space for newline and string terminator
    char buffer[16] = { 0 };

    int input[MAX_INPUT_LEN] = { 0 };
    size_t input_size = 1; // 0 is our start value

    while (fgets(buffer, 16, file)) {
        insert_value_sorted(input, &input_size, atoi(buffer));
    }

    // Add our device's built-in joltage adapter
    insert_value_sorted(input, &input_size, input[input_size - 1] + 3);

    fclose(file);

    /* Removed the 2 first values so we don't need to add 2 to our index every time
        Longest consecutive input is 5 */
    const static int TRIB[] = { 1, 1, 2, 4, 7 };
    int con = 0;
    size_t res = 1;

    for (size_t i = 1; i < input_size; i++)
    {
        int diff = input[i] - input[i - 1];
        if (diff == 1) {
            con++;
        }
        else {
            res *= TRIB[con];
            con = 0;
        }
    }

    return res;
}

int main(int argc, char *argv[])
{
    printf("%zu\n", bags_count(argv[argc - 1]));
}