this post was submitted on 21 Mar 2025
8 points (100.0% liked)

Advent Of Code

1032 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
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

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 2 years ago
MODERATORS
8
why should we sort 2024-day1 ? (self.advent_of_code)
submitted 1 week ago* (last edited 1 week ago) by somegeek to c/advent_of_code
 

Hi guys.

I just did day1 of 2024 (I know, I'm late) this might be a dumb question but I reallydont understand why we should sort the two lists before substracting? I created some test cases with 10-20 items and calculated them manually, if you don't sort the list and just add all list1 items and substract from the sum of list2, you get the same answer. But it doesn't work with the large input file.

Let's say list1 has elements (a,b,c,d) and list2 has (e,f,g,h).

(a-e)+(b-f)+(c-g)+(d-h) = a-e+b-f+c-g+d-h = (a+b+c+d)-(e+f+g+h)

So the sorting shouldn't matter. Right? But it does. Am I too bad at basic math?

top 5 comments
sorted by: hot top controversial new old
[–] [email protected] 3 points 1 week ago (1 children)

It doesn't ask you to subtract the numbers, but to calculate the distance (i.e. the absolute value of the subtraction). So depending on which numbers are paired up, the sign of the pair can be different.

[–] somegeek 2 points 1 week ago* (last edited 1 week ago) (2 children)

True, that is what I did when substracting the sorted lists. I calculated their absolutes.

But I still don't understand why the unsorted method doesn't work. Can you give an example of two lists which this method doesn't work with? Because whatever example I calculated, it was correct.

[–] [email protected] 2 points 1 week ago

There's a way to make two length-two lists from 1, 2, 3, 4 that will give you a counter-example.

[–] [email protected] 1 points 1 week ago* (last edited 1 week ago) (1 children)
10   1
 2  20

gives 27

But

 2  1
10  20

gives 11

[–] somegeek 2 points 1 week ago

You are right. Although the way I was talking about is |(2+10)-(1+20)|= 9 Seems like I coincidentally created some example lists that all worked with this method!

And the algebraic reason would be the presence of parenthesis. |(a+b)-(c+d)| != |(a-c)|+|(b-d)|