Created
December 1, 2024 14:22
-
-
Save tatut/14210928506385407fdfd812e3d70e5e to your computer and use it in GitHub Desktop.
AoC2024, day1 PostgreSQL 17
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH | |
lines AS ( | |
SELECT regexp_split_to_array(line,' ') AS ns | |
FROM regexp_split_to_table(pg_read_file('/tmp/day1.txt'),'\n') line), | |
nums AS ( | |
SELECT ns[1]::integer as l, ns[2]::integer as r FROM lines), | |
lefts AS ( | |
SELECT l as n, row_number() over(order by l) as pos FROM nums), | |
rights AS ( | |
SELECT r as n, row_number() over(order by r) as pos FROM nums) | |
-- PART 1 | |
SELECT sum(abs(n1.n - n2.n)) AS answer | |
FROM lefts n1 JOIN rights n2 ON n1.pos=n2.pos | |
UNION ALL | |
-- PART 2 | |
SELECT SUM(n1.n * (SELECT COUNT(n) FROM rights n2 WHERE n2.n=n1.n)) AS answer | |
FROM lefts n1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment