#import "Basic";
#import "File";
#import "String";
#import "Sort";

solve_day9 :: (test: bool) {
    contents := read_entire_file("inputs/day9.txt");
    lines := split(contents, "\n");

    print("Part 1: %\n", solve(lines, false));
    print("Part 2: %\n", solve(lines, true));
}

solve :: (lines: []string, part2: bool) -> s64 {
    numbers: [..]s64;
    defer array_free(numbers);

    result := 0;

    for line: lines {
        array_reset_keeping_memory(*numbers);
        start  := 0;
        offset := 0;

        numbers_split := split(line, " ");

        for numbers_split {
            if it.count == 0  continue;
            array_add(*numbers, string_to_int(it, 10, s64));
        }

        if part2 array_reverse(numbers);

        accum := numbers[numbers.count - 1];

        less := 1;

        while true {
            for 0..numbers.count - less - 1 {
                numbers[it] = numbers[it + 1] - numbers[it];
            }

            less += 1;

            accum += numbers[numbers.count - less];

            all_equal := true;

            for 0..numbers.count - less {
                all_equal = all_equal && numbers[it] == numbers[it + 1];
            }

            if !all_equal  continue;

            result += accum;
            break;
        }

    }
    return result;
}