Last active
December 6, 2021 03:16
-
-
Save philz/bc86aab13a96640f043441273af53830 to your computer and use it in GitHub Desktop.
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
// https://adventofcode.com/2021/day/5 in SQL with some algebra. | |
// I only checked this with the example, not the full data set :) | |
// | |
// Run this with `sqlite < aoc2021-day-5-sqlite.sql`. | |
WITH | |
RECURSIVE ints(v) AS ( | |
SELECT 0 UNION ALL | |
SELECT v + 1 FROM ints | |
WHERE v + 1<= 10 | |
), | |
points AS (SELECT a.v as x, b.v as y FROM ints a JOIN ints b), | |
lines(x1, y1, x2, y2) AS (VALUES | |
(0,9,5,9), | |
(8,0,0,8), | |
(9,4,3,4), | |
(2,2,2,1), | |
(7,0,7,4), | |
(6,4,2,0), | |
(0,9,2,9), | |
(3,4,1,4), | |
(0,0,8,8), | |
(5,5,8,2) | |
), | |
matching_points AS ( | |
SELECT x, y, x1, y1, x2, y2 | |
FROM points | |
JOIN lines | |
WHERE (y-y1)*(x2-x1) = (y2-y1)*(x-x1) AND (y BETWEEN y1 AND y2 OR y BETWEEN y2 AND y1) AND (x BETWEEN x1 and x2 OR x BETWEEN x2 and x1) | |
), | |
points_with_counts AS ( | |
SELECT x, y, count(*) as cnt | |
FROM matching_points | |
group by 1, 2 | |
), | |
answer AS (select count(*) from points_with_counts where cnt > 1) | |
SELECT * FROM answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment