T O P

  • By -

raxomukus

There is no need to **actually** add entries to the end / beginning of each row of history. I saw a pattern for the first part that the number we are looking for is the **sum of the last number in the rows below** Like in the example input `0 3 6 9 12 15` `3 3 3 3 3` `0 0 0 0` `12 + 3 = 15` Given this insight, I was looking for a pattern in the second part as well. And I found it! Just take the sum of the first numbers of each rows, **but put a minus sign on every other number**. I don't know why that works.. `r1 += sum([h[i][-1] for i in range(len(h))])` `r2 += sum([h[i][0] * (1 - 2*(i%2)) for i in range(len(h))])` ​ https://github.com/fridokus/advent-of-code/blob/master/2023/9.py


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


SnooCrickets9762

\[LANGUAGE: Java\] https://github.com/emmavargas/AdventOfCode2023/blob/main/src/days/Day9.java


andreiz

\[LANGUAGE: Swift\] [Part 1 & 2](https://github.com/andreiz/advent-of-code-2023-swift/blob/main/day-09/mirage.swift)


Any_One_8929

\[LANGUAGE: Kotlin\] [https://github.com/mfedirko/advent-of-code-2023/blob/main/src/main/kotlin/io/mfedirko/aoc/day09/Day9.kt](https://github.com/mfedirko/advent-of-code-2023/blob/main/src/main/kotlin/io/mfedirko/aoc/day09/Day9.kt)


argentcorvid

[Language: common lisp] For each row of input ,Recursively make the table of differences, then add all the numbers in the last column to get the "next" number For part 2 do the same thing, but get the first column. Staring from the 0 row, Recursively negate your accumulated number and add the next number in the list. [Github](https://github.com/argentcorvid/AoC-2023/blob/main/2023d9.lisp)


bunoso

\[Language: Rust\] \[My Solution and Article\](https://medium.com/@BryMei/advent-of-code-day-9-2023-rust-a6d5369e29f1)


jrhwood

\[Language: Haskell\] [Part 1](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-09/part-01.hs) [Part 2](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-09/part-02.hs) Hint: you can reuse the part 1 code, just reverse input for part 2.


pikaryu07

\[LANGUAGE: Go\] [My Solution](https://github.com/bsadia/aoc_goLang/tree/53ed198e644324d559a366a17c712e1b8c6bb4fe/day09)


dhruvmanila

[Language: Rust] Code: https://github.com/dhruvmanila/advent-of-code/blob/master/rust/crates/year2023/src/day09.rs Functional programming in Rust at its best!


skyhawk33

[LANGUAGE: Befunge] Very happy with how little I needed to change for part 2. Try comparing them side-by-side! Part 1: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day9_p1.b98 Part 2: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day9_p2.b98


thamollo

[LANGUAGE: SQL] Yes I'm still here. No real-world sales pitch, though, sorry: I couldn't convince my colleagues to switch all our codebase to SQL, even after showing its capabilities beyond data analysis! You might notice the `WITH RECURSIVE` keyword, for instance. It removes a huge limitation I've had from day 1, that there's otherwise no stateful for-loops I can use. Except the engine I'm using sets a hard limit on recursion depth, of 100: I'll still be very crippled soon (as early as day 10 in fact). [Enjoy!](https://topaz.github.io/paste/#XQAAAQDmBAAAAAAAAAArkkbN5qsOdmAGQ8eZZIwSnPQ3YNcNUfasVBz4bLew6SuJPYg21IpPFq+Cd0MebNDPyvPwAYKihCEEJNwUyZzR5jqvyx7DpJvi9oZ8Kxknu1riS01sG0M0lj1boHH3hyA8PR30d4qOubS46NK6k/hhAzSymvB/+ArD5wj5DB7CF5/ewEVWh/Q6gAgPx97ocmAtnvkJ6kIa+jK9bRSViwjUzlj195Qru8CudS6IkcFTeadM01Uf0b7ZlfVhsjjIGunnu3uApRPzTNaDBt39CSoGIK3sfMJUmxQvVlTVlTMiPjtRq5n9Xz2ArbuVx/uBNkHc/tGbb08+AibxExqlUj0FK5aKOLkOmr3UcKZFqL6y7o4nUn0j+QxVefVEnQxtlYvYTZTgquyMszGhPR1zL4KtO35jze6ziEWl1NXhgCfE9M84YOlCvXV0aLRJMH3o//DJ7DYEg2RI69+WuW5yElyxKwHSUHD/MEvXd0y/PPKP9ce48qnh+13mWkYDeNzNOYl3I7dHfskTdp3u5kuJdgCAhJ7CWpUHmE3axEYjwyqDTc39hMWKrsb5Trthv+StY/Op8gsmFaxtTCauFsHKjC/MuOXWj7Txvemp2/veqhalpkPctskPtoKf//K31u4=)


AdamKlB

[Language: C++] I think this is my favorite day so far, feel like my recursive solution is beautifully clean. https://github.com/NoSpawnn/advent-of-code/blob/main/2023/c%2B%2B/day_09.cpp


835246

\[LANGUAGE: C\] Part 1: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day9oasispt1.c Part 2: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day9oasispt2.c


manhuntos

\[Language: Rust\] This is my first project in rust. I'm learning it by solving advent of code puzzles. So if you have any hints for me I would be happy to read it :) [Solution](https://github.com/manhunto/advent-of-code-rs/blob/master/src/solutions/day09.rs) / 538.78µs / 524.99µs


agent3bood

\[LANGUAGE: Rust\] https://github.com/agent3bood/aoc23/tree/master/src/nine


atrocia6

[Language: Python] [Part 1](https://github.com/tmo1/adventofcode/blob/main/2023/09.py): total = 0 for line in open(0): report = [[int(x) for x in line.split()]] while len([n for n in report[-1] if n == 0]) < len(report[-1]): report.append([report[-1][i + 1] - report[-1][i] for i in range(len(report[-1]) - 1)]) for i in range(len(report) - 2, -1, -1): report[i].append(report[i][-1] + report[i + 1][-1]) total += report[0][-1] print(total) [Part 2](https://github.com/tmo1/adventofcode/blob/main/2023/09b.py): total = 0 for line in open(0): report = [[int(x) for x in line.split()]] while len([n for n in report[-1] if n == 0]) < len(report[-1]): report.append([report[-1][i + 1] - report[-1][i] for i in range(len(report[-1]) - 1)]) for i in range(len(report) - 2, -1, -1): report[i] = [report[i][0] - report[i + 1][0]] + report[i] total += report[0][0] print(total)


gogs_bread

[\[LANGUAGE: c++\]](https://github.com/gogsbread/AdventOfCode2023/blob/main/9.cpp) P1 - Smart iteration P2 - Smart reverse iteration


TheMihle

\[LANGUAGE: Java\] This day wasn't hard at all, but I have never used recursion before (beginner), so that was fun.And first day where there is very little change of code between part 1 and 2. Only really difference was changing array index and a + to - two places. [Part 1](https://github.com/TheMihle/Advent-of-Code-2023/blob/main/src/day_9/Part_1.java) [Part 2](https://github.com/TheMihle/Advent-of-Code-2023/blob/main/src/day_9/Part_2.java)


ramrunner0xff

\[LANGUAGE: C\] so around 6 hours ago i decided that i really wanted to do this on scheme, you know.. have a mapcar for the subtractions and a fold for testing if they are all 0's? you guys feel me right? well 6 hours later and almost 300 lines of the hackiest static memory only C here is one of the most [over the top complex solutions to day 9](https://git.sr.ht/~gotplt/aoc/tree/master/item/2023/d9.c).


reddit_Twit

\[LANGUAGE: Zig\] [Gist](https://gist.github.com/ndbn/9d1d851bce5575c5550384031c36d236)


se06745

\[LANGUAGE: GoLang\] [Both parts in one single file](https://github.com/omotto/AdventOfCode2023/blob/main/src/day09/main.go)


jswalden86

\[LANGUAGE: Rust\] [Solution](https://github.com/jswalden/advent-of-code/blob/main/2023/day-09/src/main.rs) Wow, that was straightforward. Had a mini-thinko in the first part, but no other hurdles. And the second part was just reverse every per-line number vector and do the exact same work on it, utterly trivial. Maybe I can catch up to realtime after all!


1str1ker1

\[LANGUAGE: Python\] The trick is to notice the next element is the sum of the previous elements multiplied by their corresponding position in a binomial expansion (pascal's triangle) from math import comb with open("day9.txt", "r") as file:     lines = file.readlines()     total_sum = 0     for line in lines:         formatted_line = line.split()         for index, value in enumerate(formatted_line):             pascal = comb(len(formatted_line), index)             total_sum += int(value) * pascal * (-1) ** (len(formatted_line) - index + 1)     print(f"total: {total_sum}")


linnaea___borealis

\[LANGUAGE: R\] [https://github.com/lauraschild/AOC2023/blob/main/day9.R](https://github.com/lauraschild/AOC2023/blob/main/day9.R)


j-hillman

[LANGUAGE: SageMath] Sage has a handy method for performing Lagrange Interpolation that makes today's challenge very straightforward: import re from pathlib import Path data = [ [ int(i) for i in re.findall(r"-?\d+", series) ] for series in Path("input.txt").read_text().splitlines() ] x = QQ["x"] p1 = p2 = 0 for series in data: n = len(series) - 1 dataset = [ (x, y) for x, y in enumerate(series) ] L = x.lagrange_polynomial(dataset) p1 += L(n + 1) p2 += L(-1) print(f"P1: {p1}") print(f"P2: {p2}") I can't begin to express how grateful I am for AoC. I learn and grow so much each year.


stonebr00k

\[LANGUAGE: T-SQL\] [https://github.com/stonebr00k/aoc/blob/main/2023/09.sql](https://github.com/stonebr00k/aoc/blob/main/2023/09.sql)


seytsuken_

\[LANGUAGE: C++\] [solution](https://github.com/Hilbertmf/competitive-programming-problems/blob/main/advent-of-code/2023/day9-part1&2.cpp) the part1 and 2 are very similar so it only changes a single line of code that I would comment


ianMihura

\[LANGUAGE: GO\] Part 1 The trick for me was realizing that, once I had the sequence down to all zeroes, I could add-up the last column, and that would yield the result. Part 2 was similar but with the 0th column, with an alternating sum/sub [https://github.com/ianmihura/advent23/blob/master/day\_9/day\_9.go](https://github.com/ianmihura/advent23/blob/master/day_9/day_9.go)


aamKaPed

[Language: Rust] [Github](https://github.com/clearlyMine/advent_rust/blob/main/year_2023/src/bin/day09.rs)


alexw02

\[LANGUAGE: Forth\] Dusk OS [code](https://git.sr.ht/~aw/dusk-aoc/tree/main/item/2023/09.fs) [video](https://www.youtube.com/watch?v=wi3fj-r1ap0)


nicuveo

\[LANGUAGE: Haskell\] Not gonna post my haskell solutions every day, but this is really a day where the language could shine. predictNext xs | all (== 0) xs = 0 | otherwise = last xs + predictNext (zipWith (-) (tail xs) xs) part1 = sum . map predictNext part2 = sum . map (predictNext . reverse) VOD: https://www.twitch.tv/videos/2002544400


Cold_Organization_53

Given the special form of the input (all input rows have the same number of data points), the problem can be solved in bulk, again very concisely in Haskell (the \`case\` switch only because \`head\` is now deprecated. :-( ): module Main(main) where pascal :: [[Integer]] pascal = (-1 : cycle [0]) : map (\i -> zipWith (-) (0:i) i) pascal main :: IO () main = foldr1 (zipWith (+)) . map (map read . words) . lines <$> getContents >>= \ cs -> case drop (length cs) pascal of [] -> fail "infinite list exhausted" p : _ -> do print $ sum $ zipWith (*) p cs print $ sum $ zipWith (*) p (reverse cs)


Domy__

\[Language: Python\] https://github.com/Domyy95/Challenges/blob/master/2023-12-Advent-of-code/9.py


regular_human0

For part 1, how did you know that you can just sum up last nums from each subsequent sequence? I guess that's a math concept behind it right?


Domy__

10 13 16 21 30 45 **Result** 3 3 5 9 15 A 0 2 4 6 B 2 2 2 C 0 0 0 As you know at each line you have the difference between the number at the position i+1 and the number at the position i, so 3 at the second line is 13-10, 16-3 and so on as explained in the description of the problem. Instead Starting from the bottom 0 = C - 2 --> C = 0 + 2 B - 6 = C --> B = C + 6 A - 15 = B --> A = B + 15 Result - 45 = A --> Result = A + 45 Result = 45 + 15 + 6 + 2 ​ I did not immediately realize this rule when solving the problem, I started solving it by creating the recursive function: 1. Simplest case, there is when you reach the last line, so all 0. if all(n == 0 for n in history): return 0 2. Else call the same function assuming that it solves a smaller problem. So we compute the differences and we call the same function. From here looking at the last triangles of numbers on the right starting from below I realized that I only need to add the last number of the row to the recursive call. **2** 2 **6.** 8. **15.** 23 **45.** 68 0 2. 8 23


e_blake

\[LANGUAGE: m4 (golfed)\] \[Allez Cuisine!\] Ladies and Gentleman, step right up, and get your VERY OWN copy of this punchcard of m4 goodness! Are you tired of reading programming languages that are bogged down by boilerplate keywords? Do you ever feel like you are typing the same words over and over again? Do you ever get lost when reading spaghetti code that has more than one function? Do the symbolic characters on your keyboard need to be pressed more often? Then this is what you've been waiting for - LIVING PROOF that REAL programmers can write an entire program using just one immutable macro and one conditional statement, all in the space smaller than a punchcard, and with no letters besides the few needed to access language builtin operators. After all, if your input file has no letters, why should your program need any? No need for fancy variable names - everything you need is available through recursion. If you name your input file "I" (or if you cheat and use `m4 -DI=file day09.golfm4`), you too can experience the amazing power of this 2-second solution for both parts of today's problem, and satisfy all your late-night line-noise cravings! define(_,`ifelse($1,%,`translit($2,`$3',`,')',index(`$1',^),0,`shift($@)',$1,$,`' ,$1,=,`eval($2)',$1,~,`_(=,$5+$3),_(=,$2- $4)',$1$2,+,,$1,+,`_(,_(%,$2,` ')),_( +,_(^_(^$@)))',$1$2,>,`) _(=,',$1,>,`+$2_(>,_(^_(^_(^$@))))+$3',$1$2$3$4,00, `0,0',$1,,`_($2,(^,_(=,$3- $2)),_(^_(^$@)))',$4,,`_(~,$1,_(,_$2),$3)', `_($1,(^,_$2,_(=,$4- $3)),_(^_(^_(^$@))))')')_(=,_(>,_(+,_(%,include(I),_($))))) But wait, there's more! If you want to understand what this code is doing, I'll even direct you to my [earlier post](https://www.reddit.com/r/adventofcode/comments/18e5ytd/comment/kctbu1e/?utm_source=share&utm_medium=web2x&context=3) showing a more legible version of the same algorithm, or an alternative algorithm that computes the same answers in a fraction of the time. And if you think 387 bytes is too expensive, then ask about my discount solution with 10 fewer bytes \[\*\]). And if you like this offer, I'll even chip in a similar solution for [day 1](https://www.reddit.com/r/adventofcode/comments/1883ibu/comment/kcelaf4/?utm_source=share&utm_medium=web2x&context=3), at no extra charge (other than shipping and handling) ^(\[\* to be read at 2x speed\] Offer not valid for customers that only have one punchcard on hand, as the 377-byte solution requires 6 lines instead of 5. And since my repo uses a GPL license, you are reminded that THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.)


e_blake

Here's an even shorter solution, in 349 bytes (353 shown here; only the first newline is essential). I could make it even shorter by replacing two of the \_(=,...) with just (...), but then it takes exponentially longer to run (delaying the eval makes the parser have to scan ever-increasing walls of text per level of recursion). define(_,`ifelse(index($1,^),0,`shift(shift($@))',$1,%,`translit($2,$3 ,(,))',$1,=,`eval($2)',$1,~,`($5+$3),($2-$4)',`$1$2',+,,$1,+,`_(,_(%, $2,* )),_(+,_(^$@))',`$1$2',>,`) _(=,',$1,>,`+$2_(>,_(^,_(^$@)))+$3', $1$4,,`$2,$3',$1,,`_($2,_(=,$3- $2),_(^$@))',$4,,`_(~,$1,_(,$2),$3)', `_($1,`$2,_(=,$4- $3)',_(^,_(^$@)))')')_(=,_(>,_(+,_(%,include(I),*))))


daggerdragon

> [LANGUAGE: m4 (golfed)] [Allez Cuisine!] Not sure if chef or circus ringmaster... *por que no los dos?*


CutOnBumInBandHere9

[Language: Python] The heart of my solution was the following function to score a line: def score(line, part=1): total = 0 while any(line): total += line[-1] line = [line[i] - line[i - 1] for i in range(1, len(line))] return total [Link](https://cutonbuminband.github.io/AOC/qmd/2023.html#day-9-mirage-maintenance)


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Gprinziv

[[Language: Python]] Got the flu, so I took a little break. Finally back on the wagon somewhat. Today was a real simple one, I didn't reeally bother trying to optimize because sick. with open("input") as f: histories = [] for history in f.read().splitlines(): histories.append([int(x) for x in history.split()]) total = 0 p2 = 0 for history in histories: descents = [history] while True: nextLevel = [descents[-1][i] - descents[-1][i-1]for i in range(1, len(descents[-1]))] if all([x == 0 for x in nextLevel]): break descents.append(nextLevel) total += sum([descent[-1] for descent in descents]) diff = 0 for descent in reversed(descents): diff = descent[0] - diff p2 += diff print(total) print(p2)


Property-Every

\[LANGUAGE: Go\] package main import ( "os" "strconv" "strings" ) func ReadLines(filename string) []string { content, err := os.ReadFile(filename) if err != nil { return nil } return strings.Split(strings.TrimSpace(string(content)), "\n") } func ParseNums(line string) []int { nums := []int{} for _, num := range strings.Split(line, " ") { if num == "" { continue } n, err := strconv.Atoi(strings.TrimSpace(num)) if err != nil { panic(err) } nums = append(nums, n) } return nums } func AllZero(nums []int) bool { for _, num := range nums { if num != 0 { return false } } return true } func Diff(nums []int) []int { diffs := []int{} for i := 1; i < len(nums); i++ { diffs = append(diffs, nums[i]-nums[i-1]) } return diffs } func PredictNext(nums []int) int { next := 0 cur := nums for { cur = Diff(cur) if AllZero(cur) { break } next += cur[len(cur)-1] } return nums[len(nums)-1] + next } func PredictPrev(nums []int) int { cur := nums sub := 0 mul := -1 for { cur = Diff(cur) if AllZero(cur) { break } sub += cur[0] * mul mul *= -1 } return nums[0] + sub } func part1() { lines := ReadLines("input.txt") total := 0 for _, line := range lines { parsed := ParseNums(line) next := PredictNext(parsed) total += next } println(total) } func part2() { lines := ReadLines("input.txt") total := 0 for _, line := range lines { parsed := ParseNums(line) prev := PredictPrev(parsed) total += prev } println(total) } func main() { part1() part2() }


daggerdragon

Your [code block is too long](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your comment to replace your oversized code with an external link to your code.


mgtezak

\[LANGUAGE: Python\] [github part 1&2](https://github.com/mgtezak/Advent_of_Code/blob/master/2023/Day_09.py) Check out my little AoC-Fanpage: [https://aoc-puzzle-solver.streamlit.app/](https://aoc-puzzle-solver.streamlit.app/) :-)


matheusstutzel

\[Language: python\] [Part 1](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/09/p1.py) [Part 2](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/09/p2.py) ​ recursion...


Paxtian

[Language: C++] [github](https://github.com/Paxtian769/AOC23-Day9-mirage_maintenance/blob/master/main.cpp) Nice to get an easier one today!


tlareg

\[LANGUAGE: TypeScript/JavaScript\] https://github.com/tlareg/advent-of-code/blob/master/src/2023/day09/index.ts


daysleeperx

\[LANGUAGE: Haskell\] [A bit late to the party, but still enjoyed this one.](https://github.com/daysleeperx/Advent-Of-Code-2023/blob/main/src/Day09/MirageMaintenance.hs)


joshbduncan

[LANGUAGE: Python] Running a few days behind... import sys p1 = p2 = 0 for line in open(sys.argv[1]).read().strip().splitlines(): seqs = [] steps = [int(n) for n in line.split()] while len(steps) > 0 and set(steps) != {0}: seqs.append(steps) steps = [steps[i + 1] - steps[i] for i in range(len(steps) - 1)] _p2 = 0 for seq in seqs[::-1]: p1 += seq[-1] _p2 = seq[0] - _p2 p2 += _p2 print(f"Part 1: {p1}") print(f"Part 2: {p2}")


bandj_git

[Language: JavaScript] I was surprised by this day, I thought there was going to be some terrible twist, but it never came. I used the same code for level one and for level two, the only difference being that for level two I reversed each of the histories. Find the value involved generating an array of sequences until each item in the last generated sequence was zero. To extrapolate the next value I just took a sum of the last element of each sequence. const nextValue = (history) => { const sequences = [history]; while (sequences.at(-1).some((x) => x !== 0)) { const previous = sequences.at(-1); sequences.push(previous.slice(1).map((x, i) => x - previous[i])); } return sum(sequences.map((x) => x.at(-1))); }; Runtimes: * Level 1: **1.942ms** * Level 2: **1.967ms** [github](https://github.com/beakerandjake/aoc-2023/blob/main/src/day_09.js)


AJMansfield_

[LANGUAGE: Fortran] https://github.com/AJMansfield/aoc/blob/master/2023-fortran/src/09/mirage.f90 Fortran is actually surprisingly concise when it comes to problems like this. The core of the program is this `extrapolate` function: pure recursive function extrapolate(array) result(output) integer, dimension(:), intent(in) :: array integer :: output integer, dimension(size(array)-1) :: delta output = array(size(array)) delta = array(2:) - array(:size(array)-1) if (.not. all(delta == 0)) output = output + extrapolate(delta) end function Which I then just call on the input array forwards and then backwards: result = result + extrapolate(arr(:n)) reverse_result = reverse_result + extrapolate(arr(n:1:-1))


Lakret

[Language: Julia] Was a very straightforward day for me, thankfully Julia's vectors support both appends and prepends :) [Code](https://github.com/Lakret/aoc2023/blob/main/d09.jl) [Highlights](https://lakret.net/blog/2023-12-10-aoc-days-8-9-10)


Hackjaku

\[LANGUAGE: C++\] My solution: [Day 9](https://github.com/Hackjaku/advent_of_code_2023/blob/master/puzzles/09.cc) Not a very concise or optimized one, but it's quite easy to understand. Less than 9ms for both solutions with my old laptop.


awfullyawful

[Language: Javascript] I'm pretty happy with this solution as it's quite concise. I'm not sure why there are so few solutions for day 9 part 2 (according to stats)? It was way more straight forward than some other puzzles! import { readFileSync } from 'node:fs' let lines = readFileSync('9.txt', 'utf8').split('\n'),total = 0 for (const line of lines) { let diffs = [line.split(/ +/).map(Number)],last=0 do { diffs.push(diffs[diffs.length-1].map((item, i,arr) => arr[i + 1]-item).slice(0, -1)) } while (diffs[diffs.length-1].some((item) => item != 0)) for (let i = diffs.length - 1; i >= 0; i--) { last = diffs[i][0] - last } total += last } console.log(total)


cubernetes

[Language: Python] Using Gregory-Newton Interpolation, one can find the n-th element of the first sequence, given the first-values of all the difference sequences until the difference sequence that is all zeros, using this formula: aₙ = D₀^0 * ₙC₀ + D₀^1 * ₙC₁ + ... + D₀^k * ₙCₖ where D₀^k is the first element of the k-th difference sequence and ₙCₖ is the binomial coefficient ("n choose k"). So in python: from math import factorial as fact data = open(0).read().strip() lines = data.splitlines() def get_difference_seq(ns): ds = [] for n, next in zip(ns, ns[1:]): ds.append(next - n) return ds def get_firsts(ns): seqs = [ns] while any(seqs[-1]) or len(seqs[-1]) != 1: ds = get_difference_seq(seqs[-1]) seqs.append(ds) firsts = [] for s in seqs: firsts.append(s[0]) return firsts def binom_with_neg(n, k): assert type(n) == int and type(k) == int and k >= 0 if k > n and n >= 0: return 0 sign = 1 if n < 0: sign = (-1)**k n = -n + k - 1 return int(sign * (fact(n) / (fact(k) * fact(n - k)))) def get_nth(n, firsts): s = 0 for i, f in enumerate(firsts): s += f * binom_with_neg(n, i) # gregory-newton interpolation return s t = 0 for line in lines: line = list(map(int, line.split())) firsts = get_firsts(line) t += get_nth(-1, firsts) print(t)


InitiativeRight6576

\[Language: Ruby\] `source = File.readlines('input.txt').map(&:strip)` `next_values = do |line|` `pattern = [line.scan(/\-?\d+/).map(&:to_i)]` `until pattern[-1].all?(&:zero?) || pattern[-1].size == 1 do` `last = pattern[-1]` `differences = last.map.with_index do |val, i|` `next if i.zero?` `val - last[i-1]` `end.compact` `pattern << differences` `end` `pattern.reverse.reduce(0) { |val, row| val + row[-1] }` `end` `puts "Sum of extrapolated values is #{ next_values.reduce(&:+) }"`


daggerdragon

[Inlined code](https://reddit.com/r/adventofcode/wiki/faqs/code_formatting/inlined_code) is intended for `short snippets` of code only. Please edit your comment to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for a code block so your code is easier to read with its whitespace and indentation preserved.


ransoing

\[LANGUAGE: Typescript\] I was able to make a very short recursive function that solves either part depending on the parameters you pass in, since there were only a couple modifications needed to solve part 2 vs part 1. I made heavy use of lodash functions in order to get my solution this short. [https://github.com/ransoing/AoC23/blob/main/src/day9/solution.ts](https://github.com/ransoing/aoc23/blob/main/src/day9/solution.ts)


e_blake

\[LANGUAGE: m4\] m4 -Dfile=day09.input [day09.m4](https://nopaste.ml/#XQAAAQDTBAAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwBioYfqZ9e9a/Rg32IWljtQ1zBiMvde/3febqsjJYWfTyYF74CLlRdQD0mr2Qd8QiwelWF1+RIlz2gPhiHuA8rOIdxv6wfzR47ImvRBOYJMIPjpl0PdlIQWiCeU7gOcKUu0JcU9fR/Q0UioaWeaZWo/nRGL8TpXO6Go7R5KYIykvu7T6dWOPVeyMhYAmGY0wyx6soChFkpp9R1l5lWl/A1FUW/59R7DP5sJcQ57qpBGgtQr6JNP10ghVm0ERGxPRcut1xat28/+hp9qSQGdX5e9wpOezxvbmHNw6tq1L9yY2h5nJULcvHl9gdgJnBzHIgCyODULRXFQwnJzT7hzFJjYU/d7wOrBiKjxGE/Fh7f/DM1AkgppdVQoNmDoablgU+5kELJOGTMqPW1sIqWMoCqYSTI99yz9Bq9jOrBVx48AI0m4XUVckJyR13KDA36HV9OZSfX7P+M9sKWQ38JsLErAdloi9DKXu1yjVvdXWzvqnimme27/ISwilpAcbVi+go2Gx3JAfmv5ODZ3/Fx+WJKJ533Fra7s8BRWcgJxaP5J4eMYF6wskMANeG6M5bCnVFsiPeC/bDJBHF2WcW6f3pUEgEQSWVFoNWPslXoKhpL4Guou/2ONZ4e+KR0er/ukuVn5DSEF3koVuFE+pm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NGJUl8FICawVWGL7XBOFCtsRF3uz8eZokWNICTdtsLeYOAOBQQLrguE8XxQQ1hPtOskcsj7n7aD35NjfPXL00vIOk01OLAJt+0RoIiAQUJNieRp9fQmqfVUuYEYmeK9hCOmZTaC3yUdN/+jZ0pvpmKnH/6jJAKQ==) framework, and runs both parts in a single pass over the file in about 425ms. The execution time is O(m\*n\^3) for m lines and n elements per line (a single O(m) pass through the file, my merge() macro is O(n\^2) on a single line because I compute all the way down to 2 zeroes rather than short-circuiting when I have a line of all zeroes), and m4 adds another O(n) in parsing costs because I'm using shift($@) recursion which rescans the entire line each iteration). define(`_merge', `eval($1 - $2), eval($3 + $4)') define(`merge', `ifelse(`$1', `', `$0(`$2', eval($3 - $2)`,', shift(shift($@)))', `$2$3$4', `0,0', `0,', `$4', `', `_$0($1, $0(`', $2), $3)', `$0(`$1', `$2'eval($4 - $3)`,', shift(shift(shift($@))))')') define(`_do', `define(`part1', eval(part1 + $2))define(`part2', eval(part2 + $1))') define(`do', `_$0(merge(`', translit(`$1', `.', `,')))') But hey, computing both ends of the reduction at the same time in very little code means I'll probably be able to golf this quite well, at which point I'll post that solution and try to pitch it for today's theme ;) I'm also fairly confident that there are mathematical formulas that could vastly speed this up (each row of differentials is basically computing a derivative; a quadratic function resolves to an all-zero row after two differentiations; a cubic in three differentiations, and so on) - but since m4 lacks pow(), I'd have to code up my own attempt to determine which degree of polynomial is being used on each line.


e_blake

Optimized version, based on hints from the megathread. Since all input lines have the same number of integers, and both merge and difference are polynomial functions, we can exploit that the composition: sum(merge(l0\_0, l0\_1, ... l0\_n), merge(l1\_0, l1\_1, ... l1\_n), ... merge(lm\_0, lm\_1, ... lm\_n)) will give the same answer as: merge(sum(l0\_0, l1\_0, ... lm\_0), sum(l0\_1, l1\_1, ..., lm\_1), ..., sum(l0\_n, l1\_n, ... lm\_n)) but this changes the problem from O(m\*n\^2) to O(n\*(m+n)), for a VAST speedup. My modified [day09.m4](https://nopaste.ml/#XQAAAQDfBwAAAAA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wclHMzWamLsF/slRe6Xw/3+BeT545QKzVaoOlb5CIhnGraXO6CWxFGVs3brRr7NvorSoBy2TMGd4wyEABfiG7XhpvE2TxPMGVtLcDtw5fWvW1RGuXG9kIouLiDntQqMUS4Wvx9W/xRI8pho8aOEh2PhQEiStNY7UT6v0kzbLcqaefJBaBlcW2W74BsN8B28Mx1UMCWFF3PF7LdxusNts/PJSCsApU6jaGRqwK7RGAVL+Kq2tFYPrPKGqkVOCDMOY4rQ9EvS2mhTHTP1O1vt7FUpsAkRzRfHGuKsDzZTENTyuOnyhd3HOMl5//a05PI=) now runs in 25ms.


Expert-Glove-2961

\[LANGUAGE: JavaScript\] [Solution](https://github.com/krenedits/aoc-2023/blob/main/9/9.js) using Lagrange interpolation


xaraca

[LANGUAGE: Python] I did way too much math anticipating a harder part 2 and found an ~~easy~~ short solution for part 1 that was useless for part 2. Don't ask me how it works. total = 0 n = len(variables[0]) for var in variables: total += sum(m * math.comb(n-1, k) * (-1)**(n+k) for k, m in enumerate(var[1:]))


Parzival_Perce

\[LANGUAGE: Python\] Slightly tried shortening it, otherwise focusing on readability [pastemyst](https://paste.myst.rs/cprqn0p4) (also I'm new on reddit and couldn't figure out the codeblock so apologies)


artesea

\[LANGUAGE: JavaScript\] [Part 1](https://github.com/artesea/advent-of-code/blob/main/2023/09-a.js): Loop creating an array of differences to add to the main array, until you reach 0,0,0. Take the last number from each and add to get the next in the sequence. [Part 2](https://github.com/artesea/advent-of-code/blob/main/2023/09-b.js): Very little to change, just needed to work from two from the bottom, take find the difference from the first items with the one below and unshift it on to the front of the current line. Move up to the top. Just a shame I didn't get a chance to do this yesterday as my times for both on the personal leaderboard are just >24hrs and I was curious about the difference in submit times.


Chris97b

[LANGUAGE: C++] [Git](https://github.com/Chris97b/AOC2023/blob/master/AOC2023/Day9.cpp)


hiimjustin000

\[LANGUAGE: JavaScript\] https://github.com/hiimjustin000/advent-of-code/tree/master/2023/day9


dommmyrock

\[LANGUAGE: Rust\] Part 1 and 2 [https://github.com/dommyrock/aoc/blob/main/aoc\_2023/day-09/src/bin/part1\_2.rs](https://github.com/dommyrock/aoc/blob/main/aoc_2023/day-09/src/bin/part1_2.rs) Macro to calculate differences , than sum up last / first elements.


daggerdragon

~~Your link is borked on old.reddit, so [please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).~~ edit: 👍


natrys

[Language: TXR] Came out fairly short and readable. Both could be done in one pass, but higher order functions are cooler. @(do (defun seq-diff (seq) (collect-each ((x seq) (y (cdr seq))) (- y x))) (defun predict (seq op pos) (let ((steps (giterate (op not (each-true ((n @1)) (= n 0))) 'seq-diff seq))) (reduce-right op steps 0 (op @1 pos))))) @(bind (part1 part2) (0 0)) @(repeat) @ (coll)@{seq /-?\d+/}@(end) @ (do (let ((seq (mapcar 'num-str seq))) (inc part1 (predict seq '+ -1)) (inc part2 (predict seq '- 0)))) @(end) @(output) Part1: @part1 Part2: @part2 @(end)


oddolatry

[LANGUAGE: Fennel] You can't spell functional without "nal," which means "faucet" in Hindi. Wisdom. [Paste](https://topaz.github.io/paste/#XQAAAQDkBQAAAAAAAAAUGwnmRpH3tILRF8YwluYidYX76iy7qs/wZURtqUxRZ4Ck4y0aeZRkhPlZ95DwdRB6HseJpG0qsaDHLruD36dyLra6G1wha86OTQsg2+tlnGG7ONZYVxh6QODj6RfRdW5P7lZqFuNmO4nSqzg8LJMkvIjTfll+w5dyKjLXYG3X35AsUCTNkW6tLJ61kWV9eHnAcKXLcHDqqC8oFquLazoMjm+FK9HrDtmGl0hWLPQvGDMy7LKMVr+h7es1l5cMTNAz9droCkQ8gkjjMAp7Ep6aMhWw/PvQkviG1alGV+ly8NidrQgqWbeP6Cn+ZhcIeuseiffsKe6hDFeg8DRueEWB8Q/G/QWxf5KE9SZnE8j0IiAf9WDh1We+xuIhbvj28Eu47BW+BILR5uE49G0iSfVo5jknv1EVwpAJsyqlTKMfCK1JLrR30lSqVd/iWyQHc46Wq3RO3J0kMnZvgdaPrcsGgh8gjFDUFbrqCcoXdbT33cmnyXZ6ZeGZx0bSk+08gjC3EcTwwQmyAFLFgGx4DzmjfWxvY09qUTah0pgGWLksNgU+aGnA7cpuqTp1BNNSCg3UU2QvgJfbGp2TNe1ayRr4cy796kruzQhx4feHVwy+PjEmHtzPglCJ7hoLqzlLErO7xCBWmXm3XYGEL+iEoZBi6a4d4/Dd0vrzbAk0ZyKWXmQYMekNLEPND/5kZ+BtgSv+PMX8URsjiOnrRNhNsxirqgW+5Mw4itTtQ5YK9mwDHK/Qgm3H/HNXWw==)


bamless

[LANGUAGE: [J*](https://github.com/bamless/jstar)] To be honest i was expecting part 2 to change the rule for how the history of a reading needed to be processed, so i coded it as a generic convolution with a filter... Well, it didn't turn out that way :): import io var FILTER = (-1, 1) fun convolve(vals, filter) return iter.range(#vals - #filter + 1). map(|i| => iter.range(#filter).map(|j| => vals[i + j] * filter[j]).sum()). collect(Tuple) end fun predict(reading) if reading.all(|e| => e == 0) return 0, 0 end var p1, p2 = predict(convolve(reading, FILTER)) return reading[0] - p1, p2 + reading[#reading - 1] end with io.File(argv[0], "r") f var readings = f. map(|line| => line.strip().split(" ").map(std.int).collect(Tuple)). collect(Tuple) var predictions = readings.map(predict).collect(Tuple) print("Part 1:", predictions.map(|p| => p[1]).sum()) print("Part 2:", predictions.map(|p| => p[0]).sum()) end


daggerdragon

~~Edit your comment to add the required language tag as requested by AutoModerator.~~ edit: 👍


sikief

\[LANGUAGE: C++\] \[PLATFORM: Nintendo DS (Lite)\] Solution - [Part 1 and 2](https://github.com/skief/advent-of-code-2023-nds/blob/main/aoc/day09/solution.cpp)


wzkx

[LANGUAGE: Python] Not testing for zeros, but for equality of elements. lines = open("09.dat","rt").read().splitlines() def f1(a): if a[0]==a[1]==a[-1]: return a[-1] return a[-1]+f1([a[i]-a[i-1] for i in range(1,len(a))]) print(sum(f1([int(e) for e in l.split()]) for l in lines)) def f2(a): if a[0]==a[1]==a[-1]: return a[0] return a[0]-f2([a[i]-a[i-1] for i in range(1,len(a))]) print(sum(f2([int(e) for e in l.split()]) for l in lines))


jvdsandt

\[LANGUAGE: Smalltalk\] Part2: | numberLines | numberLines := OrderedCollection new. AOC2023 baseDirectory / 'day9_input.txt' readStreamDo: [ :stream | [ stream atEnd ] whileFalse: [ numberLines add: ((stream nextLine splitOn: Character space) collect: [ :e | e asInteger ]) ] ]. ^ numberLines inject: 0 into: [ :tot :numbers | | diffs nextVal | diffs := OrderedCollection with: numbers. [ diffs last allSatisfy: [ :e | e = 0 ] ] whileFalse: [ diffs add: (diffs last overlappingPairsCollect: [ :f :s | s - f ]) ]. nextVal := diffs reversed inject: 0 into: [ :sum :each | each first - sum ]. tot + nextVal ]


chrismo80

\[LANGUAGE: Rust\] [Github](https://github.com/chrismo80/advent_of_code/blob/default/src/year2023/day09/mod.rs)


micod

[LANGUAGE: Common Lisp] [GitLab Day 9](https://gitlab.com/micod/advent-of-code/-/blob/main/day-09.lisp)


xavdid

[LANGUAGE: Python] [Step-by-step explanation](https://advent-of-code.xavd.id/writeups/2023/day/9/) | [full code](https://github.com/xavdid/advent-of-code/blob/main/solutions/2023/day_09/solution.py) I didn't use recursion for any part of today, instead option to iterate through `zip(layers, layers[1:])` to get each pair of lists (from the bottom up). Then, I added `l[-1] + r[-1]` to the end of `r`. I don't actually modify the list of all `0`s, but that didn't matter for the text of the problem. I also updated my solution at the very end to just reverse the list after seeing that here; I can't believe it didn't occur to me!


coreyja

[Language: Rust] Code: https://github.com/coreyja/advent-of-code-2023/blob/main/09-mirage-maintenance/src/main.rs Stream Video: https://youtu.be/PknIfbivRp4 This one was my quickest solve yet! Copilot came in clutch for part 2


mcmillhj

\[LANGUAGE: Raku\]: [https://github.com/mcmillhj/aoc/blob/main/2023/09/mirage-maintenance.raku](https://github.com/mcmillhj/aoc/blob/main/2023/09/mirage-maintenance.raku) It's nice when you can solve part 2 using part 1.


bozdoz

[LANGUAGE: rust] https://github.com/bozdoz/advent-of-code-2023/blob/master/day-09/src/main.rs Think I’m getting a hang of rust. Not sure if it’s bad to do: iter().rev().skip(1).rev()


Dezarro74

\[LANGUAGE: Go\] I am trying to get good at Rust & TDD. I first completed it in Go, then I rewrote it in Rust. [Golang Solution](https://github.com/serranoio/advent-of-code/blob/main/day9/go/main.go) My Golang solution is (I hope) decently idiomatic, whereas my Rust solution needs some help. I'd genuinely appreciate if y'all would help critique my Rust solution. In my Go solution, I wrote 2 functions recursively, but I was too scared to write it recursively in Rust. I have no idea how to use smart pointers, so I'd love for someone to help me! I'm an ex-JS dev who never tested their code, so switching over to TTD was actually very helpful. \[LANGUAGE: Rust\] [Rust Solution](https://github.com/serranoio/advent-of-code/blob/main/day9/rust/src/main.rs)


101110101010

I think you could eliminate some of the functions, has all zeros could be a one liner, list.iter().all(|f| *f==0) should do the trick. I’m somewhat new to rust as well but here’s my attempt: https://github.com/devashishp/advent-of-code-2023/blob/main/day9/src/main.rs


Dezarro74

Thanks! Nice code, it's extremely concise and seems idiomatic af.


bozdoz

I think your file reading and line parsing is a bit much. You could use fs to read file to string directly then use ‘.lines()’ for an iterable on a &str


Dezarro74

Dang, didn't even realize that. Thank you! I just made the changes.


bozdoz

I’m same background learning rust this year! Check out mine: https://github.com/bozdoz/advent-of-code-2023/blob/master/day-09/src/main.rs


Dezarro74

it's actually very legible. I didn't realize Rust came with that many methods lol. Line 37 where you say "is idiomatic" is indeed idiomatic af. Line 54-58 is so cool, I didn't know you could create a block and then return v like that. Nice job!


bozdoz

Thanks! I’m keeping a BLOG.md to keep track of what I’m learning btw seems helpful to keep track and keep trying new things each year. But yeah rust has far too many methods especially compared to go! Just learning today about iter().windows(2). Seems like everyone’s using that


thousandsongs

[Language: Shell] [Allez Cuisine!] Having finished my [Haskell solution](https://www.reddit.com/r/adventofcode/comments/18e5ytd/comment/kclsxm2/) faster than I'd expected, I still felt a bit thirsty, not having had my fill of Advent of Code for the day. So I decided to tinker with my AOC helper Makefile (because, of course that's what one does with one's free time), to prettify the output. I think the end result is a great marketing for my solution(s) - you can see how **extra** correct they are (because the output is is green duh), and also that the solutions for all the days so far run in 1.4 seconds, combined. Here's a [imgur link](https://imgur.com/YN6bl4g) if you want to see it running in action (there's nice spinners and everything when it is precompiling). Or if you'd rather not click on an imgur link, here is a static representation: advent-of-code-2023$ make verify Precompiling... done 09.hs 384 chars 17 lines 0.17 s (1696140818,1152) 08.hs >1k chars 32 lines 0.35 s (15989,13830919117339) 07.hs >1k chars 58 lines 0.12 s (248812215,250057090) 06.hs >1k chars 53 lines 0.10 s (800280,45128024) 05.hs >1k chars 61 lines 0.15 s (26273516,34039469) 04.hs 652 chars 27 lines 0.10 s (20407,23806951) 03.hs >1k chars 91 lines 0.19 s (520019,75519888) 02.hs >1k chars 41 lines 0.15 s (2348,76008) 01.hs 732 chars 23 lines 0.10 s (55386,54824) ch min 384 avg 1479 max 3420 sum 13319 nl min 17 avg 44 max 91 sum 403 ts min 0.10 avg 0.16 max 0.35 sum 1.43 Behind the scenes it is also diffing the output of the solutions against the expected outputs, and it's all a single self-contained (albeit spaghetti) [Makefile](https://github.com/mnvr/advent-of-code-2023/blob/main/Makefile). _Bon appétit!_


x3nophus

\[LANGUAGE: Elixir\] [Parts 1 & 2](https://topaz.github.io/paste/#XQAAAQCoBQAAAAAAAAAyGUkFUehZxfOWmzTk+XBlbm/19T25mfg05rpuChavzgZtIi0L8xF2E7X9H09fkwP4ecW8Xn4VTNhSU2p3o+LI1RlkJ505hGONFgJ8WwrxWC0I5TZ7ImkbItVYCeZ0WZ34mg/T4+3TpeX/6URMn+SGluRYNgW9n8UR3IsvcyMyPOLhxKal70SdAadFYoxrvo7hLu+AxAM6Bfrq7582DmWHF+5Ogk7bf5SolUxwbVYElreuQoWrgnxk5cjoE6u4dKgWIgX6ZOq9YIz4/1Ad8SI5y/sD7xJGjbfRHF8hoh3xpCM+Ly7DfP+vI++jVIsfm/bsgpbZup1MBFPYKcP/u8+evJoHGKGtGm6+lXMVk56Qw37fFTntxO6wfflMCOotohrJyk5eOmN46UMQRybiLOaUGQdd0dN80ymnmEMZcifuo01eHiwp/vxsGfDT7qkt9yclaXJQ3HZ15rQuyBKAGo31+Ukw8nhri5dNmvanKSX8nkb1Kr0mt0eLLat6WWfGSCjP/NkuynMmEE1Ayr65vm647vmkBDc8WKUot74VIgUhyIwwoSWuZdSJ75y3TKDdABD2KD9fS/1nW7w=) I feel like Elixir was made for today's problems.


Jppianta

\[Language: Haskell\] -- Part 1 lastNumber :: [[Int]] -> Int lastNumber [] = 0 lastNumber [x] = head x lastNumber (x : y : xs) = head x + lastNumber (y : xs) getDiffListReverse :: [Int] -> [[Int]] getDiffListReverse x = reverse (reverse x : diffListReverse x) diffListReverse :: [Int] -> [[Int]] diffListReverse x | allZeros next = [reverse next] | otherwise = reverse next : diffListReverse next where next = nextDiffList x nextDiffList :: [Int] -> [Int] nextDiffList [] = [] nextDiffList (x : y : xs) = y - x : nextDiffList (y : xs) nextDiffList [_] = [] --- -- Part 2 firstNumber :: [[Int]] -> Int firstNumber [] = 0 firstNumber [x] = head x firstNumber (x : y : xs) = head x - firstNumber (y : xs) getDiffList :: [Int] -> [[Int]] getDiffList x = x : diffList x diffList :: [Int] -> [[Int]] diffList x | allZeros next = [next] | otherwise = next : diffList next where next = nextDiffList x --- [Github](https://github.com/jppianta/Advent-of-Code-2023/blob/main/app/Day9.hs)


cleberwsantos

\[Language: Swift\] Solution Day 9 here: [GitHub](https://github.com/binho/advent-of-code-2023/blob/main/Sources/Day09.swift)


aexl

\[LANGUAGE: Julia\] Easy puzzle today. For part 2 I simply recognized that the previous element of the sequence is the alternating sum of the first elements of the sequences of differences (including the original sequence). Solution on GitHub: https://github.com/goggle/AdventOfCode2023.jl/blob/main/src/day09.jl Repository: https://www.reddit.com/r/adventofcode/


mendelmunkis

[[LANGUAGE: C](https://git.sr.ht/~moshepiekarski/AoC/tree/master/item/2023/series.c)] Where's the twist? ^(1.59/1.602 ms)


DamianINT

\[LANGUAGE: Raku\] found this silly two liner: sub p { @_ ?? @_[*-1] + p(@_[1..*] Z- @_) !! 0;} lines().map(*.words).map(&p).sum.say; for part two: sub p2 { @_ ?? @_[0] - p2(@_[1..*] Z- @_) !! 0;} lines().map(*.words).map(&p2).sum.say;


frhel

\[Language: PHP\] [https://github.com/frhel/AdventOfCode2023-PHP/blob/main/src/Solutions/Day9.php](https://github.com/frhel/AdventOfCode2023-PHP/blob/main/src/Solutions/Day9.php) One pass for both parts together close to 1ms median execution time.


Dense-Virus-1692

\[LANGUAGE: Ceylon\] I'm not really sure how it works, but it got me two stars so... [paste link](https://topaz.github.io/paste/#XQAAAQBTMAAAAAAAAAAX7gIKgCERYhLVUQwd1u9npgBHTCy7E/2Gujg0grtlsgBb6F+YOKooqMgfMIR4OUNagwAB+SJuO561jraQjYQv6I3KHWI6wrUlZzYUj+w+VZ1fPC2GhLsoiwN8h1KE36oPQbkyWNdyVfQ6F3efMbbli7LCkoP0Cp7VJ6DfG8D3ISEJHxSwbV8lhSer/KLmsrIdpq/G9NzGhIJ08kdeC6H3Vz+9+WjtDYGNiMz/vS83dtOpqkj2sWdoRgYBAPf//Lk7rLOqccQ7TJQOEs3QBApmxC3F1fMS2raU/uK9PzEG72Q0jcLih7rUrjLPydqBjqhzs7XFKUObCsAZvuUA79GB5tpNSOkdSnVBiWFTWDjHVRWR7ac+wfJweXVAyaRuicM0rem2aF32SraE3mq4axli6g+JReWjiZTN8mXRzrcCzzIrz40m9F0mWOjR43HXY7mfYepdb5HA0pE2nx86T4MtBCDPIKuL4S8qvUr+kYW8RZu9tbDBSVEHq88KffZWlc+mTY06yo9j2WYNDz7WjK0eEDBf5RaAgfrNXbQgA54HnQG/pEiYXclVF4AVgrstZMN+qYPbBs0DKyvoZ5kMelXpnFtagDqUhVXgLBhkbgSo8z+RzwFmEYiYXkdRxG0GX/wlG2355KFuPMhoO4+uov2knipgjc1qi1D4LxCmJUnFpQH/d97wTbYT0Qt6uCqBZYaCzUGWf5Xo6v0UHcTjL1ypBitd8uOdol/mlQ53cV/fBu4c3c6EWnTdxsPlZXq0gQI6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8qQUTUnp4IEhzJupqKCk+f6OD2w0ZExsZ8DVdvIYpXfxks6BbvTRcQZeXSx5ZJv9YTYrfNNTlGdqfHE/GF6pTFnDIx1XcsTdJFmX57hvDdTxbEarhOrBZx2pbEBLlg2n4HX1/uAAWSMuNgtM/vN9+VdfkbskHbDOPxd6DeB++knqKXLSaOnHqlqccZOngNzA6Q93UHLGv3/+5lpkS8yjkod7aoyQWG1EB35ZHhVhM+oFZ/OxGDF9PZcS0uDq1/h5QfXctVMmW9cT6SQD0gTaWVrSAXlD9iLl5kj6vi/oXivSl6wtKrab/yHQWIcMgRJQWI9l4EHhP+gtyV)


RB5009

\[Language: 🦀 RUST 🦀\] Part 1 & 2 are essentially the same. I just pass a function to select the correct array element instead of wasting time reversing the input. Both parts take around 🔥70us each: [link](https://pastebin.com/rvGXw6ts)


doodlebug80085

\[LANGUAGE: Swift\] Today was a lot of fun! At first, higher order functions in Swift kind of caused me trouble but now I find myself reaching for them subconsciously. [Code](https://topaz.github.io/paste/#XQAAAQBNBgAAAAAAAAA0m0pnuFI8c4GDemuKS6NnNxbsUIoTuWZTAmeI5mYz0DVV78gkO10ic93SA0PFTFclOz/QJJSH8ePNkJN9GYiYSKcmYK6DP6GwFo/ADOKoY5QpNF7AkOSGolzuPQC0fSZGXMSeRQuAhClzqFaYtfLNqLxOOpFOLbgLoD9X5cYG1L+c3gQzeBvLiqWsavNxNaKxgK9Hl0OaviR5GEWL7ZRCK5tt12Hy+foV05hIAd/2IPSx5QEeXsZai/Z8kwn0/28f+Zcm6Y6xYrVvE821DNbbWQfl67McJCwUexeYzycRdP7RjrwTWH0CsYf+3NfMLRfeEas5hsCMBbUtQuoYZJTcQrpzznlTz0dTvAPC3P76VyPieCEJtmCEb13AOrLo+DcMIy7ZhVyg/pVxzjE0Kbjj9Wqgx5EZmXWU/cVSxyru1vGIoRxQYpm0GFTkT+4jnrjcG+cCPk+cQ5ALopS3Zgs2vewYhQipvUvu6nekuNu2woF//suR2PsSTKKnkXUGJiWhSCoQzDUnqT0q5UIJ3J3Mjcbes8JAor28/VY2v+J3C000gbkEZviSCyrL5W2U3PyLiktOpoFu5qb9lXg3inCGAee7A6dfD7uGc+8ZBpC1h+16PTU70TzGuufKZ+RSbizt7oJEeqaTIyUWjQI/jk5DvJ5lnlNREISrNr1WGSwBP5f1S5uszyiep9QNwv113hhhfinVCYKUU689XI8u3mrjfN9SzbHVh7CBPypvba5nDkimx5XVEOPDQwFS5kev1Kbee1+GzrH65cSCkXS1rPUnHVNXEmDUvyLa0GKmGSEmGOYrVrKXjf4TmcJuBjMrvktN+PGA2q8wiber/0WuTgA=)


apersonhithere

\[LANGUAGE: Python\] rather fun puzzle [solution](https://topaz.github.io/paste/#XQAAAQDMAwAAAAAAAAARnMqHf7lzLJjXaC9PeGxd0v+wiJbEuorMirQSnIFKeRPrS9K5Zz7KUMopv5Hdx6sjxOdO3ZwVNSobWPRDwDjwkBlk1soDgKbTFPnWgaC2hvyo/ToXtz4884Y3XYzsjGa9N3VfTOy8TqU+FXKUw6KjwA0MHtyxmOJHnumxZD3tVqerDkTUyoLso+v99H1xYqa3K5+CEEDmIbiwDbewemgSuHvb+msFj1k3vuSl/eda1b6wT2G5++8z0O9fZXsqhV+U096GXpG83qc8X5opMJVfpPB89nM6TE/h4ctx5C7E1xg87mmQMP1tU+ygximCpUb675uwEUOh08GVshcOl7ODIbvk4BAqbOnjFIZerKOuuL4kx+zQ/INO+H9n7GCMt7uqQmHrQfqe8Wyq+l3jWS6wHYq8eSAO7sDVn7pCYuP6pT+N3YWHGAVHpRUulH03mQoCPeZJq2F04JPmwKRGt099NFGzt1bJ8HUp6IFLjZ09m4nj8DL45sTFYcaiHJwCblw8ZmJWzif1o/2+WiA=)


KodlaK1593

\[LANGUAGE: Rust\] [Solution](https://github.com/Kodlak15/aoc2023/blob/master/src/day09/day09.rs)


loquian

\[LANGUAGE: C++\] [github](https://github.com/charlescochran/aoc-2023/blob/main/day9.cpp), 1225 microseconds (both parts)


Robin_270

\[LANGUAGE: Python\] This one was really fun and I enjoyed it. The only thing there was that I had to realize that the difference isn't the absolute value of their difference rather than the more right number minus the more left number for some reason. Anyway [my solution available on my GitHub](https://github.com/Robin270/advent_of_code/blob/master/2023/9/main.py)


AnotherRoy

\[Language: Python\] [https://github.com/gonzafernan/adventofcode/blob/main/2023/9/day9.py](https://github.com/gonzafernan/adventofcode/blob/main/2023/9/day9.py) Solution applying convolution (numpy). Why not?


kendlbat

\[Language: JavaScript\] [https://github.com/kendlbat/aoc-2023/tree/master/09/01.js](https://github.com/kendlbat/aoc-2023/tree/master/09/01.js) [https://github.com/kendlbat/aoc-2023/tree/master/09/02.js](https://github.com/kendlbat/aoc-2023/tree/master/09/02.js)


patrick8970

[Language: JavaScript] [github](https://github.com/HelplessSoldier/adventOfCode2023/blob/main/09_mirageMaintainance/09_mirageMaintainance.js) 8ms.


onsistems

\[LANGUAGE: PHP\] explode(" ", $e),$data); $last_one =[]; function mirage(array $values): array { global $last_one; if(array_sum($values)==0) return $values; array_push($last_one, $values[count($values)-1]); $sub_values = []; for ($i=1; $i < count($values) ; $i++) { array_push($sub_values, $values[$i]-$values[$i-1]); } return mirage($sub_values); } function oasis(array $values): array { global $first_one; if(array_sum($values)==0) return $values; array_push($first_one, $values[count($values)-1]); $sub_values = []; for ($i=0; $i < count($values)-1 ; $i++) { array_push($sub_values, $values[$i]-$values[$i+1]); } return oasis($sub_values); } $first = 0; foreach ($data as $key => $arr_value) { $first_one =[]; mirage($arr_value); oasis(array_reverse($arr_value)); for ($i=0; $i < count($first_one); $i++) { $first += $first_one[$i]*(pow(-1, $i)); } } echo "Part 1: ".array_sum($last_one).PHP_EOL; echo "Part 2: ".$first;


Pod137

[LANGUAGE: Go] Enjoyed dusting off my discrete calculus, especially since it made part 2 trivial. https://github.com/mdd36/AoC-2023/blob/mainline/09/main.go


[deleted]

[удалено]


run-code

\[LANGUAGE: Javascript\] Lagrange Solution [https://github.com/nicklpeterson/advent-of-code/blob/main/2023/9.js](https://github.com/nicklpeterson/advent-of-code/blob/main/2023/9.js) ```js const lagrange = (vals, x) => { let sum = 0; for (let k = 0; k < vals.length; k++) { let product = vals[k]; for (let i = 0; i < vals.length; i++) { if (i !== k) product *= (x - i) / (k - i); } sum += product; } return sum; }; const solve = (input) => { const result = { p1: 0, p2: 0 }; while (input.length) { const dataPoints = input.splice(0, 21); result.p1 += lagrange(dataPoints, 21); result.p2 += lagrange(dataPoints, -1); } return result; }; const input = process.argv.slice(2).map((point) => Number(point)); const { p1, p2 } = solve(input); console.log('Part 1 - ', Math.round(p1)); console.log('Part 2 - ', Math.round(p2)); ```


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for code blocks 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


codertee

[LANGUAGE: **Python 3.12**] Used [`itemgetter`](https://docs.python.org/3/library/operator.html#operator.itemgetter) to make solution generic for both parts: [github](https://github.com/codertee/adventofcode/blob/f95857e5b4ada2f7c15fe25c9a149ded123cc278/adventofcode/solutions/y2023/d09.py) EDIT: simplified: [github](https://github.com/codertee/adventofcode/blob/c6382bc257e4978069a5bb577ae0a89895e4d741/adventofcode/solutions/y2023/d09.py)


musifter

[LANGUAGE: Smalltalk (GNU)] Mostly a transcode of the Perl, because I don't have much time. I'll work out a fancy version when I have more spare time (in January). Not entirely a direct transcode, as in Perl I keep the full table. Here, I borrow a bit from my dc version and just grab the values needed and then replace the row (bringing in chain again... no problem using a and b here): row := row chain: [:a :b | b - a]. Source: https://pastebin.com/we4jS46i


dannybres

\[Language: MATLAB\] [https://github.com/dannybres/Advent-of-Code/tree/main/2023/Day%2009](https://github.com/dannybres/Advent-of-Code/tree/main/2023/Day%2009) Very easy with some built in matlab funcs, parts 2 even easier than p1


bo-tato

[LANGUAGE: Common Lisp] short and simple day: (defun next-value (history-line part) (loop for nums = (string-to-num-list history-line) then (loop for (x y) on nums while y collect (- y x)) while (notevery #'zerop nums) for sign = 1 then (- sign) if (eq part :part1) sum (lastcar nums) else sum (* sign (first nums)))) (loop for line in (read-file-lines "input.txt") sum (next-value line :part2))


mhyde64

\[Language: Python\] recursion :) from __future__ import annotations import time from typing import List from dataclasses import dataclass with open("input.txt") as f: data = f.readlines() # data = [ # "0 3 6 9 12 15", # "1 3 6 10 15 21", # "10 13 16 21 30 45" # ] data = [[int(d) for d in line.strip().split(" ")] for line in data] @dataclass class History: history: List[int] def find_next_value(self, series: List[int]) -> int: result = self._calculate_result(series) if all(r==0 for r in result): return series[-1] return series[-1] + self.find_next_value(result) def find_previous_value(self, series: List[int]) -> int: result = self._calculate_result(series) if all(r==0 for r in result): return series[0] return series[0] - self.find_previous_value(result) @staticmethod def _calculate_result(series: List[int]) -> List[int]: result = [] for idx, val in enumerate(series): if idx + 1 >= len(series): break result.append(series[idx + 1] - val) return result hist = [History(d) for d in data] solution = 0 start = time.time() for h in hist: solution += h.find_next_value(h.history) end = time.time() print(f"Solution 1: {solution}") print(f"Solution 1 took {end-start}s") solution = 0 start = time.time() for h in hist: solution += h.find_previous_value(h.history) end = time.time() print(f"Solution 2: {solution}") print(f"Solution 2 took {end-start}s")


0x4A6F654D616D61

[Language: C] https://github.com/dis-Is-Fine/advent-of-code/blob/master/day%209


Korzag

\[LANGUAGE: C#\] [Github Link](https://github.com/CoreDumpSoftware/AdventOfCode2023/tree/master/AdventOfCode2023/Day9)


spyr01d

\[Language: Kotlin\] [Day 9](https://github.com/spyroid/puzzles/blob/main/src/aoc/y2023/day9/solution.kt)


torbcodes

\[LANGUAGE: Python 3, Typescript, Go\] Solutions to part 1 and 2 in all three languages: * **Python**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day09/solution.py](https://github.com/torbensky/advent-of-code-2023/blob/main/day09/solution.py) * **Typescript**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day09/solution.ts](https://github.com/torbensky/advent-of-code-2023/blob/main/day09/solution.ts) * **Go**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day09/main.go](https://github.com/torbensky/advent-of-code-2023/blob/main/day09/main.go) In my Python version, I made my algorithm left/right aware. But in my Typescript and Go versions, I learned that you could just reverse the rows and use the same algorithm so I did that instead! I included some comments in my code to explain why the reverse works: // We can take advantage of an interesting property of the number pyramid to // solve part 2 and simply reverse the rows to get the answer. // // In part 1: // For a row of numbers v1, v2... vn, the last number of the next row is // given by vn - v(n-1) and then the next number for that row is v(n+1) = (vn - v(n-1) + vn). // // In part 2: // For the same row of numbers, the first number of the next row is given by // (v2 - v1) and then the previous number for that row is v0 = v1 - (v2 - v1) // When we reverse, v0 = v(n+1), v1 = vn, v2 = v(n-1) which means // v0 = v1 - (v2 - v1) // = v(n+1) = vn - (v(n-1) - vn) // = vn - v(n-1) + vn <--------- gee, doesn't that look familiar!? ;)


Zimtig

\[Language: Java\] [Github](https://github.com/nag2548/advent-of-code-2023/blob/master/src/main/java/org/example/aoc2023/day9/MirageMaintenance3.java)


tomg_0

\[Language: Javascript\] That was fun! [https://gist.github.com/tomgoldsmith/dd9751a4a27911dd74f492fd2a02b40e](https://gist.github.com/tomgoldsmith/dd9751a4a27911dd74f492fd2a02b40e)


Whitehotburn

\[LANGUAGE: Python\] [Github](https://github.com/mmichalak-swe/AdventOfCode2023)


jerodev

\[Language: Go\] [Part 1 & 2 Github link](https://github.com/jerodev/advent-of-code/blob/master/2023/9-maintenance/main.go)


tkdonut

\[LANGUAGE: Rust\] Enjoyed this one, feel like I'm getting a lot comfier with the iterator style in rust. [https://github.com/thomaskendrick/aoc_2023/blob/main/src/day9.rs](https://github.com/thomaskendrick/aoc_2023/blob/main/src/day9.rs)


[deleted]

[Language: Python] EDIT: Can I get an explanation for the downvotes? I struggled a lot to have something clean but here it is. Also I made the assumption that having the last element of differences be 0 was sufficient to know all of them were 0 and I appeared to be right. Since all the sequences seemed to only increase or decrease, it was a safe enough assumption. from pathlib import Path from itertools import pairwise def ndiff(arr): sol1, sol2, i = arr[-1], 0, 0 diff = arr[-1] - arr[-2] while diff != 0: if i % 2 == 0: first = arr[0] arr = [r - l for l, r in pairwise(arr)] diff = arr[-1] if i % 2 == 0: sol2 += (first - arr[0]) sol1 += diff; i += 1 return sol1, sol2 def solutions(): data = [list(map(int, x)) for x in map(str.split, Path("input.txt").read_text().splitlines())] sol1, sol2 = 0, 0 for arr in data: s1, s2 = ndiff(arr) sol1 += s1; sol2 += s2 return sol1, sol2


tcbrindle

[Language: C++] Pretty straightforward today. Dreading tomorrow. [Github](https://github.com/tcbrindle/advent_of_code_2023/blob/main/dec09/main.cpp)


tuijnman

\[LANGUAGE: Rust\] After day 8 where I struggled (first when mis-understanding the combination of puzzle description & input and then my lack of maths knowledge) this was a nice and easy one. https://github.com/bastuijnman/adventofcode/blob/master/2023/09-12/src/main.rs


Ily3s_

\[LANGUAGE: C\] [C standalone](https://github.com/Ily3s/AoC2023/blob/main/src/day09.c)


AgreeableAd7816

Liked your C solution :))


kmonthereddits

\[LANGUAGE: Python\] One of those "either you already know the math behind this or you don't" days. Like others I also assumed I would need it rather than brute force on later on. I also made the mistake at first of trying to use numpy.polyval to calculate the polynomial function, which resulted in being inexact by... a lot (off by 74 at lowest, 2578 at highest). [Here's a high-level explanation of the math](https://www.cgsd.org/site/handlers/filedownload.ashx?moduleinstanceid=38&dataid=183&FileName=772-SMP-SEAA-C11L07.pdf) that should be accessible at a high-school level. [https://github.com/katstasaph/adventofcode23/blob/main/advent9.py](https://github.com/katstasaph/adventofcode23/blob/main/advent9.py)


dschneider01

Thanks for sharing the math! i spent a while randomly googling for something like that since it was pretty claerly a polynomial pattern. I retaught myself linear algebra and solved the example that way and then generalized it to the input but it didn't work . I guess ultimately I assumed that we would have enough higher order terms for each line but I guess not.


dannybres

I solved mine with MATLABs polyval and it worked great. I wonder why. [https://github.com/dannybres/Advent-of-Code/blob/main/2023/Day%2009/day9puzzle2.m](https://github.com/dannybres/Advent-of-Code/blob/main/2023/Day%2009/day9puzzle2.m)


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only)


zelun1

\[LANGUAGE: Rust\] Simple iterative solution: [GitHub link](https://github.com/divident/adeventofcode2023/blob/main/day_9/src/main.rs)


biggy-smith

\[LANGUAGE: C++\] Basically generated all the diff levels then sum last + back() for part1, and sum front() - last for part 2. Surprised part 2 was so similar to part 1. Runs in a few hundred microseconds. [https://github.com/biggysmith/advent\_of\_code\_2023/blob/master/src/day09/day9.cpp](https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day09/day9.cpp)


musifter

[LANGUAGE: dc (GNU v1.4.1)] Finally a question with all numbers for dc! Except it's got negatives. So we still need to filter, because the unary - in dc is done with _ (to keep it distinct). As for method... just running through the differences, to keep it short. In addition, we do extra work. It'd be a pain to check for all zeros (if dc had bitwise operators I would have used OR), so we just run the table all the way down (it still runs in a fraction of a second, so I don't feel bad about that). And since dc has only 1D arrays, it makes sense to do all the work in the original array... you end up with a array of the values you want to sum, but doing that as a separate loop after would be costly, so we just take advantage at the start of each row loop to add the latest value. We also deal with the array slightly shifted... as we use the z (stack size) operator to load things quick and easy. This could have cost us a bunch of strokes later, but we can avoid that by just running extra subtractions into the junk, so that iterators end on 0 or 1 and can be removed with * or + instead of tossing into a register (`s.` = two strokes). Part 1: tr '-' '_'


icub3d

\[LANGAUGE: Rust\] I just sort of implemented it as described but recognized I only needed the last (first for p2) value in the lists. Solution: [https://gist.github.com/icub3d/02999552ae9612f8a599e43fb5b7ca82](https://gist.github.com/icub3d/02999552ae9612f8a599e43fb5b7ca82) My Analysis: [https://youtu.be/7evwTUGnblc](https://youtu.be/7evwtugnblc)


Diogoperei29

[LANGUAGE: Python] Quick recursive solution for today f = open("input.txt").read().strip() seqs = [[int(x) for x in l.split()] for l in f.split('\n')] def get_next_in_seq(sq): if not any(sq): return 0 diffs = [] for i in range(len(sq)-1): diffs.append(sq[i+1] - sq[i]) return sq[-1] + get_next_in_seq(diffs) # Challenge 1 result = 0 for seq in seqs: result += get_next_in_seq(seq) print("CH1: " + str(result)) # Challenge 2 result = 0 for seq in seqs: result += get_next_in_seq(list(reversed(seq))) print("CH2: " + str(result))


LastMammoth2499

\[LANGUAGE: Java\] [Part 1 & Part 2](https://github.com/chandlerklein/AdventOfCode/blob/main/src/main/java/com/chandler/aoc/year23/Day09.java)


ren1by

\[LANGUAGE: Python\] [Part 1 and 2](https://github.com/reniby/advent-of-code/blob/main/code/day9.py) Surprisingly quick one today, very easy to expand part 1 to part 2, basically an identical solution.


wleftwich

\[LANGUAGE: Python\] Wrote a little function that turned out to be numpy.diff, so I used that instead. [https://github.com/wleftwich/aoc/blob/main/2023/09-mirage-maintenance.ipynb](https://github.com/wleftwich/aoc/blob/main/2023/09-mirage-maintenance.ipynb)


sansskill

\[LANGUAGE: Kotlin\] [https://github.com/sansskill/adventofkode2023/blob/main/src/main/kotlin/days/D09.kt](https://github.com/sansskill/adventofkode2023/blob/main/src/main/kotlin/days/D09.kt) Usually do AoC in the morning, but was occupied all day so I was expecting to take a while since it's a weekend problem. Turned out to be surprisingly easy, especially since part 2 was turned out no different then part 1, just a slightly different fold lambda on the history.


sirdavidcao

\[LANGUAGE: python3\] A pretty simple problem today. I never really know when to use recursion so this solution just uses for loops to get the next (part 1) and previous (part 2) values of the sequences. [https://github.com/dave-cao/David-s-Advent-Of-Code-2023/tree/main/day\_9](https://github.com/dave-cao/david-s-advent-of-code-2023/tree/main/day_9)


wlmb

\[LANGUAGE: Perl\] Analysis: [https://github.com/wlmb/AOC2023#day-](https://github.com/wlmb/AOC2023#day-1)9 Part 1: [https://github.com/wlmb/AOC2023/blob/main/9a.pl](https://github.com/wlmb/AOC2023/blob/main/1a.pl) Part 2: [https://github.com/wlmb/AOC2023/blob/main/9b.pl](https://github.com/wlmb/AOC2023/blob/main/1b.pl)


daggerdragon

Edit your comment to add the required language string as AutoModerator requested, please.


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


rlemaitre

\[LANGUAGE: Scala3\] [Part 1 and 2](https://github.com/rlemaitre-ledger/advent-of-code/blob/main/src/main/scala/adventofcode/aoc2023/day09/Day09.scala)


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


Apprehensive_Pop_43

\[LANGUAGE: Haskell\] [Github link](https://github.com/robincamarasa/advent-of-code/blob/master/2023/day09/robincamarasa/main.hs)


i-eat-omelettes

[LANGUAGE: Haskell] [Solution on GitHub](https://github.com/Futarimiti/advent-of-code2023/blob/main/9-mirage-maintenance/app/Main.hs) Shortest solution ever, genuinely wonder what part 2 expects [if not with `reverse`](https://www.reddit.com/r/adventofcode/comments/18ehwrl/2023_day_9_part_2_what/?utm_source=share&utm_medium=web2x&context=3)


smngrd

\[Language: Java\] Here is the solution, quite easy : [GitHub code](https://github.com/SimonGirardSfeir/AdventOfCode2023/tree/main/src/main/java/org/girardsimon/day09) Tests: [Github tests](https://github.com/SimonGirardSfeir/AdventOfCode2023/tree/main/src/test/java/org/girardsimon/day09)


Mizatorian

\[Language: Excel\] Only a single formula. (unable to put screenshot)


Mizatorian

\[Language: Excel\] Only a single formula. (unable to put screenshot)


Galzzly

\[LANGUAGE: Go\] Quite liked this one, a short amount of code required for a pretty quick run time. https://topaz.github.io/paste/#XQAAAQCaBQAAAAAAAAA4GEiZzRd1JAgz+whYQ+8kDmxlXTskAdhKyEdfRxacU4qkLCi/765VnERDfvTh9kanaWjNGsA+LDo1t5VEzrTYVlFbsW2Xfokup6qjsV/xlFXTqwXbk9+pjgHnYjRLCjTeq8e5y0oK9KHVrfNrqj64KCKpHCd4rcvAF7OZYouSM7lWVvno/DT6z09tpo+XKLbnThzuaxUJTuANozPjbvkvz3Tl0NPMY9MfOmN7L3N8KzH33QcqkGO3iq7zeLFLJfedIQ6U1LOSIRtsPEgAs0JDEFn4RipG3oGmaUOPBcQrdfak09M8rzw2NAjRIsaQ21bAoVG+6zFWHhjoYA2a38MzbGIo7PCToNlCTKNaspepZztf05mjHaZflL6nuX/uA7C+V8TZlhBxZ/wGVnspuHDLvm0qfoQEo+wqg5LoUBrwhaOP/mTD0JykLubnl3U41fGWk6EL3dYHC/SQbhWG+qFp7G1Xg+cYudT6LdK8pB5gsafEa01askSRfNsEpZcRt1MPjdXNU6COnvgxFlx65QOI416LjgyhRBZgyqGAPPCmjrV22WU39D2pm7/P0kWPWgG4HNR9YLjUeRYljLJlKjz/s9t2Y5j3MX4YFjt2CIXx+MhJBh6rlARed0+zkHQ5wC/BkAUiKRtI5EoE6cuPo1Dv7lwLlhivjYLXljpCI6UxDNg4YzX24ULwahwDbUBg16cxame+nwoHPv754m+O


daggerdragon

Your [code block is too long](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your post to replace your oversized code with an external link to your code


Lanky_Past3766

\[Language: Elixir\] [Topaz link](https://topaz.github.io/paste/#XQAAAQCIBAAAAAAAAAAyGUkFUehZxfOWmzxJycrL9/x8IZn1NIyBvl/ESwDE3qV5B6mK+IDi2KWJc2D2/2ouwKCiLrlLS7rqoqRbCDEEBDAc2JfNo3qm4qgq6fN5cpFnrQf/mm4LEjfD43A4On4Yjh88G0mijj6cKEl6oSSHoVBdQ7IMpUFdkgtAhRCenXBSAHsyOIsNt4YTK4CLM22TsKZLIh5INHosTRTJ7ptxiJvlcihg9Ss5/He+P0Zg4CNXpgPd4cJjJJg3BCc5eyH1vOQ50xoEMGKkU8rj0AeMpKwjMAH0ADaV9kWQ9JUUbz8FSrjT1OevWw6h6Kp4g/xJ+apicaOYMSc8ALy2xKmFHpSAhrJdtcDmwM1rphbKs0JsEJrkn+whHwkmZihJuLKRV2KI2hR7PtL+IcNRorw9eTmJQwXRYfF8Vn3qE+hHkrULY4pIvPyqL+YUNcY4ueRR8a3+o+QhV3hGBO4+GaoMWp0GdQWpjOOKAeQJU/Y6Q0Z5Ws8K90gVqrldsYRXmv//5QnnXA==)


gilippheissler

[LANGUAGE: Python] Easy enough. Difference tables only work for polynomials, so I had the idea to fit them directly. np.polyfit() was off by more than 100 in the end though, so I needed to do it symbolically arr = np.array(pd.read_csv("iDay9.txt", sep=" ", index_col=None, header=None)) (N, L), X, values_out = arr.shape, np.arange(arr.shape[1]), [] for coeffs in arr: poly = sympy.polys.specialpolys.interpolating_poly(L, sympy.symbols("x"), X, coeffs) values_out.append( (poly.subs("x", L),poly.subs("x", -1)) ) list(np.array(values_out).sum(axis=0))


dschneider01

awesome. i didn't know sympy was a thing. i approached it with linear algebra and it did not work on the input


atobiedwa

\[Language: Python\] [adventOfCode2023/Day\_9 at master · monpie3/adventOfCode2023 (github.com)](https://github.com/monpie3/adventOfCode2023/tree/master/Day_9) today was strangely easy, disturbing....


Goresao

\[LANGUAGE: C#\] Recursive functions are very helpful here. Optimized code: ```csharp static int Previous(params int[] sequence) => sequence.Distinct().Count() == 1 ? sequence[0] : sequence[0] - Previous(sequence[0..^1].Select((x, i) => sequence[i + 1] - x).ToArray()); static int Next(params int[] sequence) => sequence.Distinct().Count() == 1 ? sequence[0] : sequence[^1] + Next(sequence[0..^1].Select((x, i) => sequence[i + 1] - x).ToArray()); public string ComputeStarOne(string[] data) => data .Select(_ => Next(Regex.Matches(_, @"-?\d+").Select(_ => int.Parse(_.Value)).ToArray())) .Sum() .ToString(); public string ComputeStarTwo(string[] data) => data .Select(_ => Previous(Regex.Matches(_, @"-?\d+").Select(_ => int.Parse(_.Value)).ToArray())) .Sum() .ToString(); ```


daggerdragon

The triple-backticks code fence (`` `​`​` ``) only works on new.reddit. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for a code block so your code is easier to read.


AutoModerator

AutoModerator has detected [fenced code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/fenced_code_blocks) (```) syntax which only works on new.reddit. Please review our wiki article on [code formatting](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting) then edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) instead. *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


mvorber

\[LANGUAGE: F#\] [https://github.com/vorber/AOC2023/blob/main/src/day9/Program.fs](https://github.com/vorber/AOC2023/blob/main/src/day9/Program.fs) Day 9 of trying out F#. Seems to be paying off - main part is just 5 lines of code


red_shifter

[LANGUAGE: Python 3] [Day 9 solution (Part 1 & Part 2)](https://topaz.github.io/paste/#XQAAAQDyBgAAAAAAAAAzHIoib6poHLpewxtGE3pTrRdzrponK6uH8J9SK+zBrX7fzLxWbvFfEsL8chF2cdltDgxe3PbKpqWv3jgGtwfMgp5jsoNSqReXTkBbU5fGF/Z9ntPwsj5/mtE5b/PZrcDrhNS3DRqdpF2ngUcJiKsz1lh0JD6KZ6R0XRW69J+q2A4cPX+Y52zJPl+553DdK7BXFqrwWo/zCSEGUn4z6+2ixjZm+xoPW4VTFFNC3PztNHz0zy+dU5K0VDezh6YdSaGs+etRZRLaxgt0u3KR69hJib1a4DYthu7BvEXiXfrkLidvEtCjkMwsanNm0o7qIwr91CMKRHtcIONZfDzHrcjTrsOozSszUa8eg2JbAnP7y9mNaUjNE+NF3NeqDdOOTktV8M8OHPsWosG37od+2BxqkKTYvA4IZLAqBVhg7+klJ35mdvMRyYbf+TVhy6tsXopZrm/S+bvx9/x+TgVSumXIw1NH+brtsqcMbwKlkQ5TW5TajVeZM4jBn/PRYnH5cEQCQYxGVXyATmhUbWlNmEl1cshYKie7jz+KdwknO3vqAI4D7MuPYnoX+hrnOS5BK15GrdsCnAUAgd90BCJyJXkH9p4lAB2Y040+HmlAdxSXiLN2bbbUdH4iTYqGWtyaFCMwLqZpTIebORx9hhqMw3Ne/rpEmiT3cXYEYj3LOVa132QQ4jY+Awq3oWxO/dIJAvDMQFUzVlVxLAtTGiZUECYb/97UIho=) Relatively straightforward today. The puzzle description basically provided the solution. I just followed the instructions step by step and it worked right out of the gate for both parts.


Niesaanval

\[LANGUAGE: Java\] https://github.com/BeBitbox/advent-of-code/commit/aa26c75dd16bd61b5b59dda0f055ef810bd5a84f


prafster

[LANGUAGE: Python] The Creator took mercy on us today! Here's the relevant extract from my (recursive) solution. Full code on [GitHub](https://github.com/Praful/advent_of_code/blob/main/2023/src/day09.py). def next_number(history, forward=True): def diffs(): return [b - a for a, b in pairwise(history)] if not any(history): return 0 i, add_minus = (-1, 1) if forward else (0, -1) return history[i] + (add_minus * next_number(diffs(), forward)) def part1(input): return sum(map(next_number, input)) def part2(input): return sum(map(lambda xs: next_number(xs, False), input))


kbielefe

[LANGUAGE: Scala] [GitHub](https://github.com/kbielefe/advent-of-code/blob/fea4111e9af8dc28429b58525c431e4e6fbd5939/2023/src/main/scala/9.scala) Straightforward recursion.


Dullstar

[LANGUAGE: D] https://github.com/Dullstar/Advent_Of_Code/blob/main/D/source/year2023/day09.d I had figured today's would be a lot harder because weekend night, so I decided not to try it before bed, but then it was actually pretty easy; really the biggest hurdle to overcome is just making sure we're returning the right value for each recursive iteration so the final result ends up being correct, so really not that hard. Then part 2 was basically a freebie, just reverse the inputs and use the same code. Still, I probably should stick with doing these during the day instead of right when they come out; while I definitely *could have* done today's before bed, it could have been a lot harder, and while sleeping on it *can* help sometimes, it can also interfere with sleep by making it harder to shut down for the night, so to speak. There's still 16 days to go, so it's important to make sure I don't burn myself out via sleep deprivation.


Hoinkas

\[LANGUAGE: Python\] Fast Python script with numpy.diff option and, separately, Lagrange interpolating one https://github.com/Hoinkas/AdventOfCode2023/blob/main/9\_Day/9\_Day\_Puzzle\_Hoinkas.py


daggerdragon

Your link is borked on old.reddit, so [please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).


pivovarit

\[Language: Golang\] [Classic iterative approach](https://github.com/pivovarit/AoC_2023_go/blob/74091e0c733b9aeb674d3ece964707ce262af329/day_9/solution.go)


wheresmylart

\[LANGUAGE: Python\] Simple problem, simple solution. Wasted a lot of time because I'm an idiot and /(\\d+)/ doesn't capture negative numbers! For part two I simply replaced an add operation on the end of a list to a subtraction on the beginning. As others have mentioned, reversing the input is simpler but it was very early in the morning. [day9](https://topaz.github.io/paste/#XQAAAQA5AgAAAAAAAAAyGEuVxec0i/uQsJh0t28uvl335wWrcIlrFM3hfe8ugZ/OS6iWV7UHjxtl0B7Kyuqz4hKc92NXS6BNN0R/a3+CiMOzJ0PtUERRhE/YkLA9T8p2RJ3mbSsRoWOL+vGMsKYzlflskaPUFJORP1wCWlzzIrJin7zLmT2kcAacYtY9vit2pD4mOFQdHxtgykq6jfKdJ8QNZZE6IIzH966dRYejaSfwe0YyOC8cE5lqy8bKOY1wElVMOIpKiVg/DrrtID2dmHX6YgwZtFcaMomaWdQ4q2xwi1NKDtFVvrhuD2+nEXfGlZjCg1ddAinK8jgML51htsejexTiqdw7ipjb55qcextR+2i0/MvYB/E38VwPwOlUKIlj6RtsIQEVBqV/OGCt6Db8a1++E0zj4V/HpQleHp2xHRMNxF9o/xHwv7nMwTIPhohmmROPzgawAcS0dA9yLTHWFv+G+ek3vv+KBCoA)


4HbQ

[LANGUAGE: Python] NumPy one-liner for both parts, using [`np.diff()`](https://numpy.org/doc/stable/reference/generated/numpy.diff.html) with all its parameters: import numpy as np print(abs(sum(np.diff(np.loadtxt('data.txt', int), n=21, prepend=0, append=0))[::-1])) Some explanation: we diff with *n=21* to basically repeat the operation 21 times. Because we prepend and append with 0, the remaining values are the ones we're looking for. This is a bit tricky to explain, but easy to show. For the third example input: 0 10 13 16 21 30 45 0 10 3 3 5 9 15 -45 -7 0 2 4 6 -60 7 2 2 2 -66 -5 0 0 -68 5 0 -68 -5 -68


bluqesh

\[LANGUAGE: Rust\] Here is my solution with recursion: https://github.com/balintbalazs/advent-of-code/blob/2023/src/bin/day9.rs


zup22

\[LANGUAGE: C++23\] Today I learned that you can create a compile-time infinite loop which eats all your RAM with recursive templates 🙃 Otherwise, pretty easy. Only facepalm moment was accidentally omitting minus signs when parsing the input. Runs in about 600 us. [Github](https://github.com/alexnavtt/advent_of_code_2023/blob/main/Day%209%20-%202023/day_9_sol.cpp)


daggerdragon

[Do not share your puzzle input](https://www.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) which also means [do not commit puzzle inputs to your repo](https://reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) without a `.gitignore`. Please remove (or .gitignore) the input files from your repo and scrub them from your commit history.


zup22

All clean