11defmodule AdventOfCode.Day17 do
22 def part1 ( args ) do
3-
4- % { x1: x1 , x2: x2 , y1: y1 , y2: y2 } = Regex . named_captures ( ~r/ .*x=(?<x1>[0-9\- ]*)\. \. (?<x2>[0-9\- ]*), y=(?<y1>[0-9\- \. ]*)\. \. (?<y2>[0-9\- \. ]*)/ , args )
5- |> Enum . map ( fn { k , v } -> { String . to_atom ( k ) , String . to_integer ( v ) } end )
6- |> Map . new ( )
7- start = { 0 , 0 }
3+ % { x1: x1 , x2: x2 , y1: y1 , y2: y2 } = parse ( args )
84 target = { x1 .. x2 , y1 .. y2 }
95
106 { x , y } = range ( x1 , x2 , y1 , y2 )
117
128 { highest , _velocity } =
139 Enum . reduce ( x , { - 1_000_000 , { 0 , 0 } } , fn vx , { bestest_height , _v } ->
1410 Enum . reduce ( y , { bestest_height , { vx , 0 } } , fn vy , { best_height , best_vel } ->
15- { final_pos , new_height } = try_velocity ( start , { vx , vy } , target )
11+ { final_pos , new_height } = try_velocity ( { 0 , 0 } , { vx , vy } , target )
1612 max_height = max ( best_height , new_height )
1713 cond do
1814 inside_target? ( final_pos , target ) and new_height == max_height ->
@@ -29,8 +25,8 @@ defmodule AdventOfCode.Day17 do
2925
3026 @ spec range ( number , number , number , number ) :: { Range . t ( ) , Range . t ( ) }
3127 def range ( x1 , x2 , y1 , y2 ) do
32- y = max ( abs ( x1 ) , abs ( x2 ) )
33- x = max ( abs ( y1 ) , abs ( y2 ) )
28+ y = max ( abs ( x1 ) , abs ( x2 ) ) * 3
29+ x = max ( abs ( y1 ) , abs ( y2 ) ) * 3
3430 { - x .. x , - y .. y }
3531 end
3632
@@ -85,5 +81,30 @@ defmodule AdventOfCode.Day17 do
8581 end
8682
8783 def part2 ( args ) do
84+ % { x1: x1 , x2: x2 , y1: y1 , y2: y2 } = parse ( args )
85+ target = { x1 .. x2 , y1 .. y2 }
86+
87+ { x , y } = range ( x1 , x2 , y1 , y2 )
88+
89+ Enum . reduce ( x , [ ] , fn vx , vs ->
90+ new_vs = Enum . reduce ( y , [ ] , fn vy , velocities ->
91+ { final_pos , _new_height } = try_velocity ( { 0 , 0 } , { vx , vy } , target )
92+ case inside_target? ( final_pos , target ) do
93+ true ->
94+ [ { vx , vy } | velocities ]
95+ false ->
96+ velocities
97+ end
98+ end )
99+ [ new_vs | vs ]
100+ end )
101+ |> List . flatten
102+ |> Enum . count
103+ end
104+
105+ def parse ( input ) do
106+ Regex . named_captures ( ~r/ .*x=(?<x1>[0-9\- ]*)\. \. (?<x2>[0-9\- ]*), y=(?<y1>[0-9\- \. ]*)\. \. (?<y2>[0-9\- \. ]*)/ , input )
107+ |> Enum . map ( fn { k , v } -> { String . to_atom ( k ) , String . to_integer ( v ) } end )
108+ |> Map . new ( )
88109 end
89110end
0 commit comments