Code for the Advent of Code event
aoc
advent-of-code
1#!/usr/bin/env ruby
2# frozen_string_literal: true
3
4require 'matrix'
5
6class Vector
7 def x = self[0]
8 def x=(v)
9 self[0] = v
10 end
11
12 def y = self[1]
13 def y=(v)
14 self[1] = v
15 end
16end
17
18X_RANGE, Y_RANGE = ARGF.read.scan(/-?\d+\.\.-?\d+/).map { eval _1 }
19
20def test(x_range, y_range, velocity)
21 position = Vector[0, 0]
22 max_y = 0
23 loop do
24 position += velocity
25 return false if position.y < y_range.min
26 max_y = position.y if position.y > max_y
27 velocity.x += velocity.x > 0 ? -1 : 1 if velocity.x != 0
28 velocity.y -= 1
29 return [true, max_y] if x_range.include?(position.x) && y_range.include?(position.y)
30 return false if position.x < x_range.min && velocity.x <= 0
31 return false if position.x > x_range.max && velocity.x >= 0
32 end
33end
34
35successes = 0
36max_y = 0
37
38(1..X_RANGE.max).each do |x_vel|
39 # magic max range found by experimentation
40 (Y_RANGE.min..Y_RANGE.min.abs).each do |y_vel|
41 vel = Vector[x_vel, y_vel]
42 success, max = test(X_RANGE, Y_RANGE, vel)
43 next unless success
44 successes += 1
45 max_y = max if max > max_y
46 end
47end
48
49puts max_y
50puts successes