@@ -10,6 +10,12 @@ defmodule Whales do
1010
1111 def  distance_to ( a ,  b ) ,  do:  abs ( a  -  b ) 
1212
13+  def  increasing_distance_to ( a ,  b )  do 
14+  1 .. abs ( a  -  b ) 
15+  |>  Enum . to_list ( ) 
16+  |>  Enum . sum ( ) 
17+  end 
18+ 1319 def  find_cheapest_route ( positions ) , 
1420 do:  find_cheapest_route ( positions ,  Enum . min ( positions ) ,  nil ) 
1521
@@ -37,6 +43,37 @@ defmodule Whales do
3743 end 
3844 end 
3945
46+  def  find_new_cheapest_route ( positions ) , 
47+  do:  find_new_cheapest_route ( positions ,  Enum . min ( positions ) ,  nil ) 
48+ 49+  def  find_new_cheapest_route ( positions ,  target ,  cheapest )  do 
50+  # This takes a while, so we add debug output 
51+  IO . inspect ( target ,  label:  "Target" ) 
52+  IO . inspect ( Enum . count ( positions ) ,  label:  "Positions" ) 
53+ 54+  if  target  >=  Enum . count ( positions )  +  1  do 
55+  cheapest 
56+  else 
57+  current  = 
58+  if  target  ==  Enum . max ( positions )  +  1  do 
59+  cheapest 
60+  else 
61+  positions 
62+  |>  Enum . map ( fn  position  ->  increasing_distance_to ( position ,  target )  end ) 
63+  |>  Enum . sum ( ) 
64+  end 
65+ 66+  new_cheapest  = 
67+  if  current  <  cheapest  do 
68+  current 
69+  else 
70+  cheapest 
71+  end 
72+ 73+  find_new_cheapest_route ( positions ,  target  +  1 ,  new_cheapest ) 
74+  end 
75+  end 
76+ 4077 @ spec  first ( )  ::  Integer 
4178 def  first ( )  do 
4279 positions  =  load_file ( "../input.txt" ) 
@@ -45,6 +82,8 @@ defmodule Whales do
4582
4683 @ spec  second ( )  ::  Integer 
4784 def  second ( )  do 
85+  positions  =  load_file ( "../input.txt" ) 
86+  find_new_cheapest_route ( positions ) 
4887 end 
4988end 
5089
0 commit comments