File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ ExUnit . start ( )
2
+
3
+ defmodule Whales do
4
+ def load_file ( path ) do
5
+ File . read! ( path )
6
+ |> String . split ( "," , trim: true )
7
+ |> Enum . map ( & Integer . parse / 1 )
8
+ |> Enum . map ( & elem ( & 1 , 0 ) )
9
+ end
10
+
11
+ def distance_to ( a , b ) , do: abs ( a - b )
12
+
13
+ def find_cheapest_route ( positions ) ,
14
+ do: find_cheapest_route ( positions , Enum . min ( positions ) , nil )
15
+
16
+ def find_cheapest_route ( positions , target , cheapest ) do
17
+ if target == Enum . max ( positions ) + 1 do
18
+ cheapest
19
+ else
20
+ current =
21
+ if target == Enum . max ( positions ) + 1 do
22
+ cheapest
23
+ else
24
+ positions
25
+ |> Enum . map ( fn position -> distance_to ( position , target ) end )
26
+ |> Enum . sum ( )
27
+ end
28
+
29
+ new_cheapest =
30
+ if current < cheapest do
31
+ current
32
+ else
33
+ cheapest
34
+ end
35
+
36
+ find_cheapest_route ( positions , target + 1 , new_cheapest )
37
+ end
38
+ end
39
+
40
+ @ spec first ( ) :: Integer
41
+ def first ( ) do
42
+ positions = load_file ( "../input.txt" )
43
+ find_cheapest_route ( positions )
44
+ end
45
+
46
+ @ spec second ( ) :: Integer
47
+ def second ( ) do
48
+ end
49
+ end
50
+
51
+ defmodule WhalesTest do
52
+ use ExUnit.Case
53
+ end
Original file line number Diff line number Diff line change
1
+ 16,1,2,0,4,2,7,1,2,14
You can’t perform that action at this time.
0 commit comments