Skip to content

Commit 70eae77

Browse files
committed
Solve 2021 Day 7 part 1 in elixir
1 parent c50c1e0 commit 70eae77

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

2021/Day7/Elixir/whales.ex

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

2021/Day7/test.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
16,1,2,0,4,2,7,1,2,14

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy