Skip to content

Commit

Permalink
chore: work on day24b
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaxwood committed Aug 13, 2024
1 parent 28d9e2b commit de2e1b9
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
63 changes: 63 additions & 0 deletions lib/day24.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
# frozen_string_literal: true

require 'matrix'

class Point3D
attr_reader :x, :y, :z, :cx, :cy, :cz

def initialize(x, y, z, cx, cy, cz)
@x, @y, @z = x.to_f, y.to_f, z.to_f
@cx, @cy, @cz = cx.to_f, cy.to_f, cz.to_f
end

def to_s
"Position: (#{x}, #{y}, #{z}), Velocity: (#{cx}, #{cy}, #{cz})"
end
end

class Line
attr_reader :x, :y, :cx, :cy

Expand Down Expand Up @@ -36,6 +52,32 @@ def intersection_point(other_line)
end
end

def find_intersection_point(points)
return nil if points.size < 3

a_rows = []
b_elements = []

3.times do |i|
p1, p2 = points[i], points[(i+1) % 3]

d = Vector[p2.cx - p1.cx, p2.cy - p1.cy, p2.cz - p1.cz]
n = d.cross_product(Vector[p1.cx, p1.cy, p1.cz])

a_rows << n.to_a
b_elements << n.dot(Vector[p1.x, p1.y, p1.z])
end

a = Matrix.rows(a_rows)
b = Vector.elements(b_elements)

begin
a.inverse * b
rescue ExceptionForMatrix::ErrNotRegular
return nil
end
end

# Day24
class Day24
def load(file, min, max)
Expand All @@ -51,6 +93,17 @@ def load(file, min, max)
end
end

def parse(file)
content = File.read(file)
@parts = []
content.split("\n").each do |line|
f, e = line.split("@")
fs = f.split(",").map(&:to_i)
es = e.split(",").map(&:to_i)
@parts << Point3D.new(fs[0], fs[1], fs[2], es[0], es[1], es[2])
end
end

def part1
result = []
@parts.each_with_index do |part, i|
Expand All @@ -68,5 +121,15 @@ def part1
end
result.length
end

def part2
solution = find_intersection_point(@parts)
if solution.nil?
return -1
else
return soluion[0] + solution[1] + solution[2]
end
0
end
end

6 changes: 6 additions & 0 deletions test/unit/day24_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ def test_day24a
assert_equal(2, sut.part1)
end

def test_day24b
sut = Day24.new
sut.parse('data/day24a.txt')
assert_equal(47, sut.part2)
end

def test_day24
sut = Day24.new
sut.load('data/day24.txt', 200000000000000, 400000000000000)
Expand Down

0 comments on commit de2e1b9

Please sign in to comment.