Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)
Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒 Thread is locked until there's at least 100 2 star entries on the global leaderboard
Part 1:
The extrapolated value to the right is just the sum of all last values in the diff pyramid. 45 + 15 + 6 + 2 + 0 = 68
Part 2:
The extrapolated value to the left is just a right-folded difference (right-associated subtraction) between all first values in the pyramid. e.g. 10 - (3 - (0 - (2 - 0))) = 5
So, extending the pyramid is totally unneccessary.
Total runtime: 0.9 ms
Puzzle rating: Easy, but interesting 6.5/10
Full Code: day_09/solution.nim
Snippet:
proc solve(lines: seq[string]): AOCSolution[int] =
for line in lines:
var current = line.splitWhitespace().mapIt(it.parseInt())
var firstValues: seq[int]
while not current.allIt(it == 0):
firstValues.add current[0]
block p1:
result.part1 += current[^1]
var nextIter = newSeq[int](current.high)
for i, v in current[1..^1]:
nextIter[i] = v - current[i]
current = nextIter
block p2:
result.part2 += firstValues.foldr(a-b)
Pretty easy one today. Made a Pyramid type to hold the values and their layers of diffs, and an extend function to predict the next value. For part 2 I just had to make an extendLeft version of it that inserts and subtracts instead of appending and adding.
Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn't work well for people on different instances. Try fixing it like this: !nim@programming.dev
I solved the actual thing recursively in Rust, but I decided that wasn't cursed enough, so I present: Polynomial fitting!
import numpy.polynomial.polynomial as pol
with open("input.txt") as f:
lines = list(map(lambda l: list(map(int, l.split(" "))), f.read().split("\n")))
lo, hi = 0, 0
for line in lines:
for i in range(len(line)):
poly, (r, *_) = pol.Polynomial.fit(range(len(line)), line, full=True, deg=i)
if r < 0.0000000001:
break
lo += int(round(poly(-1)))
hi += int(round(poly(len(line))))
print(f"Part 1: {hi}")
print(f"Part 2: {lo}")
from .solver import Solver
class Day09(Solver):
def __init__(self):
super().__init__(9)
self.numbers: list[list[int]] = []
def presolve(self, input: str):
lines = input.rstrip().split('\n')
self.numbers = [[int(n) for n in line.split(' ')] for line in lines]
for line in self.numbers:
stack = [line]
while not all(x == 0 for x in stack[-1]):
diff = [stack[-1][i+1] - stack[-1][i] for i in range(len(stack[-1]) - 1)]
stack.append(diff)
stack.reverse()
stack[0].append(0)
stack[0].insert(0, 0)
for i in range(1, len(stack)):
stack[i].append(stack[i-1][-1] + stack[i][-1])
stack[i].insert(0, stack[i][0] - stack[i-1][0])
def solve_first_star(self) -> int:
return sum(line[-1] for line in self.numbers)
def solve_second_star(self) -> int:
return sum(line[0] for line in self.numbers)
I was getting a bad feeling when it explained in such detail how to solve part 1 that part 2 was going to be some sort of nightmare of traversing all those generated numbers in some complex fashion, but this has got to be one of the shortest solutions I've ever written for an AoC challenge.
int nextTerm(Iterable ns) {
var diffs = ns.window(2).map((e) => e.last - e.first);
return ns.last +
((diffs.toSet().length == 1) ? diffs.first : nextTerm(diffs.toList()));
}
List> parse(List lines) => [
for (var l in lines) [for (var n in l.split(' ')) int.parse(n)]
];
part1(List lines) => parse(lines).map(nextTerm).sum;
part2(List lines) => parse(lines).map((e) => nextTerm(e.reversed)).sum;
Pretty straightforward. Took advantage of itertools.pairwise.
def predict(history: list[int]) -> int:
sequences = [history]
while len(set(sequences[-1])) > 1:
sequences.append([b - a for a, b in itertools.pairwise(sequences[-1])])
return sum(sequence[-1] for sequence in sequences)
def main(stream=sys.stdin) -> None:
histories = [list(map(int, line.split())) for line in stream]
predictions = [predict(history) for history in histories]
print(sum(predictions))
Part 2
Only thing that changed from the first part was that I used functools.reduce to take the differences of the first elements of the generated sequences (rather than the sum of the last elements for Part 1).
def predict(history: list[int]) -> int:
sequences = [history]
while len(set(sequences[-1])) > 1:
sequences.append([b - a for a, b in itertools.pairwise(sequences[-1])])
return functools.reduce(
lambda a, b: b - a, [sequence[0] for sequence in reversed(sequences)]
)
def main(stream=sys.stdin) -> None:
histories = [list(map(int, line.split())) for line in stream]
predictions = [predict(history) for history in histories]
print(sum(predictions))
First time using Grammar Actions Object to make parsing a little cleaner. I thought about not keeping track of the left and right values (and I originally didn't for part 1), but I think keeping track allows for an easier to understand solution.
edit: although I don't know why @values.all != 0 evaluates to true why any value is not zero. I thought that @values.any != 0 would do that, but it seems that their behavior is flipped from my expectations.
edit2: Oh, I think I understand now. != is a shortcut for !==, and !== is actually the equality operator that is then negated. You can negate most relational operators in Raku by prefixing them with !. So the junction is actually binding to the == equality operator and not the !== inequality operator. Therefore @values.all != 0 becomes !(@values.all == 0). I'm not sure why they would choose this order of operations, though.
use v6;
sub MAIN($input) {
my $file = open $input;
grammar Oasis {
token TOP { +%"\n" "\n"* }
token history { +%\h+ }
token val { '-'? \d+ }
}
class OasisActions {
method TOP ($/) { make $».made }
method history ($/) { make $».made }
method val ($/) { make $/.Int }
}
my $oasis = Oasis.parse($file.slurp, actions => OasisActions.new);
my @histories = $oasis.made;
my $part-one-solution;
my $part-two-solution;
sub revdiff { $^b - $^a }
for @histories -> @history {
my @values = @history;
my @rightmosts = [@values.tail];
my @leftmosts = [@values.head];
while @values.all != 0 {
@values = @values.tail(*-1) Z- @values.head(*-1);
@rightmosts.push(@values.tail);
@leftmosts.push(@values.head);
}
$part-one-solution += [+] @rightmosts;
$part-two-solution += [[&revdiff]] @leftmosts.reverse;
}
say "part 1: $part-one-solution";
say "part 2: $part-two-solution";
}
Using a class here actually made part 2 super simple, just copy and paste a function. Initially I was a bit concerned about what part 2 would be, but looking at the lengths of the input data, there looked to be a resonable limit to how many additional rows there could be.
python
import re
import math
import argparse
import itertools
#https://stackoverflow.com/a/1012089
def iter_item_and_next(iterable):
items, nexts = itertools.tee(iterable, 2)
nexts = itertools.chain(itertools.islice(nexts, 1, None), [None])
return zip(items, nexts)
class Sequence:
def __init__(self,sequence:list) -> None:
self.list = sequence
if all([x == sequence[0] for x in sequence]):
self.child:Sequence = ZeroSequence(len(sequence)-1)
return
child_sequence = list()
for cur,next in iter_item_and_next(sequence):
if next == None:
continue
child_sequence.append(next - cur)
if len(child_sequence) > 1:
self.child:Sequence = Sequence(child_sequence)
return
# can't do diff on single item, use zero list
self.child:Sequence = ZeroSequence(1)
def __repr__(self) -> str:
return f"Sequence([{self.list}], Child:{self.child})"
def getNext(self) -> int:
if self.child == None:
new = self.list[-1]
else:
new = self.list[-1] + self.child.getNext()
self.list.append(new)
return new
def getPrevious(self) -> int:
if self.child == None:
new = self.list[0]
else:
new = self.list[0] - self.child.getPrevious()
self.list.insert(0,new)
return new
class ZeroSequence(Sequence):
def __init__(self,count) -> None:
self.list = [0]*count
self.child = None
def __repr__(self) -> str:
return f"ZeroSequence(length={len(self.list)})"
def getNext(self) -> int:
self.list.append(0)
return 0
def getPrevious(self) -> int:
self.list.append(0)
return 0
def parse_line(string:str) -> list:
return [int(x) for x in string.split(' ')]
def main(line_list):
data = [Sequence(parse_line(x)) for x in line_list]
print(data)
# part 1
total = 0
for d in data:
total += d.getNext()
print("Part 1 After:")
print(data)
print(f"part 1 total: {total}")
# part 2
total = 0
for d in data:
total += d.getPrevious()
print("Part 2 After:")
print(data)
print(f"part 2 total: {total}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="day 1 solver")
parser.add_argument("-input",type=str)
parser.add_argument("-part",type=int)
args = parser.parse_args()
filename = args.input
if filename == None:
parser.print_help()
exit(1)
file = open(filename,'r')
main([line.rstrip('\n') for line in file.readlines()])
file.close()
Used recursion to determine the differences for part 1 and then extracted the variations in processing from predicting the end vs. the beginning of the history and passed them in as Func variables to the recursive method.
This one was very easy, almost trivial.
Lean4 did demand a proof of termination though, and I'm still not very good at writing proofs...
I'm also pretty happy that this time I was able to re-use most of part 1 for part 2, and part 2 being a one-liner therefore.
As always, here is only the file with the actual solution, some helper functions are implemented in different files - check my github for the whole project.
Solution
private def parseLine (line : String) : Except String $ List Int :=
line.split Char.isWhitespace
|> List.map String.trim
|> List.filter String.notEmpty
|> List.mapM String.toInt?
|> Option.toExcept s!"Failed to parse numbers in line \"{line}\""
def parse (input : String) : Except String $ List $ List Int :=
let lines := input.splitOn "\n" |> List.map String.trim |> List.filter String.notEmpty
lines.mapM parseLine
-------------------------------------------------------------------------------------------
private def differences : List Int → List Int
| [] => []
| _ :: [] => []
| a :: b :: as => (a - b) :: differences (b::as)
private theorem differences_length_independent_arg (a b : Int) (bs : List Int) : (differences (a :: bs)).length = (differences (b :: bs)).length := by
induction bs <;> simp[differences]
-- BEWARE: Extrapolate needs the input reversed.
private def extrapolate : List Int → Int
| [] => 0
| a :: as =>
if a == 0 && as.all (· == 0) then
0
else
have : (differences (a :: as)).length < as.length + 1 := by
simp_arith[differences]
induction (as) <;> simp_arith[differences]
case cons b bs hb => rw[←differences_length_independent_arg]
assumption
a + extrapolate (differences (a :: as))
termination_by extrapolate a => a.length
def part1 : List (List Int) → Int :=
List.foldl Int.add 0 ∘ List.map (extrapolate ∘ List.reverse)
-------------------------------------------------------------------------------------------
def part2 : List (List Int) → Int :=
List.foldl Int.add 0 ∘ List.map extrapolate
A pretty simple one today, but fun to do. I could probably clean up the parsing
code (AKA my theme for this year), and create just one single vector instead of
having the original history separated out from all of the sequences, but this
is what made sense to me on my first pass so it's how I did it.