diff --git a/examples/aoc2024/day11/part1.jou b/examples/aoc2024/day11/part1.jou new file mode 100644 index 000000000..639b50a28 --- /dev/null +++ b/examples/aoc2024/day11/part1.jou @@ -0,0 +1,73 @@ +import "stdlib/ascii.jou" +import "stdlib/io.jou" +import "stdlib/mem.jou" +import "stdlib/str.jou" + + +# count_digits(999) = 3 +# count_digits(1000) = 4 +def count_digits(n: long) -> int: + result = 0 + while n > 0: + n /= 10 + result++ + return result + + +# split_digits(1234) == [12, 34] +def split_digits(n: long) -> long[2]: + length = count_digits(n) + assert length % 2 == 0 + + power_of_10 = 1 + for i = 0; i < length/2; i++: + power_of_10 *= 10 + + return [n / power_of_10, n % power_of_10] + + +# Returns new number of stones +def blink(stones: long*, nstones: int) -> int: + old_nstones = nstones + + for i = 0; i < old_nstones; i++: + if stones[i] == 0: + stones[i] = 1 + elif count_digits(stones[i]) % 2 == 0: + pair = split_digits(stones[i]) + stones[i] = pair[0] + stones[nstones++] = pair[1] + else: + stones[i] *= 2024 + + return nstones + + +def main() -> int: + f = fopen("sampleinput.txt", "r") + assert f != NULL + line: byte[100] = "" + fgets(line, sizeof(line) as int, f) + fclose(f) + + words = split_by_ascii_whitespace(line) + + nstones = 0 + while words[nstones] != NULL: + nstones++ + + stones: long* = malloc(sizeof(stones[0]) * nstones) + assert stones != NULL + for i = 0; i < nstones; i++: + stones[i] = atoll(words[i]) + + free(words) + + for i = 0; i < 25; i++: + # Make sure there's enough room even if every stone splits. + stones = realloc(stones, sizeof(stones[0]) * (2 * nstones)) + assert stones != NULL + nstones = blink(stones, nstones) + printf("%d\n", nstones) # Output: 55312 + + return 0 diff --git a/examples/aoc2024/day11/sampleinput.txt b/examples/aoc2024/day11/sampleinput.txt new file mode 100644 index 000000000..9b26c84c9 --- /dev/null +++ b/examples/aoc2024/day11/sampleinput.txt @@ -0,0 +1 @@ +125 17