r/o
1
defmodule Three do
2
def max_combination(list, k) do
3
map =
4
list
5
|> Enum.with_index()
6
|> Enum.map(fn {item, index} -> {index, item - ?0} end)
7
|> Enum.into(%{})
8
9
length = length(list)
10
combinations_from(map, length, k, 0, 0, 0, [], [], 0)
11
end
12
13
def combinations_from(map, length, k, acc, index, con, [lastix | ixsub], [_ | sub], sublen)
14
when index == length and lastix + 1 == length,
15
do: combinations_from(map, length, k, acc, length, div(con, 10), ixsub, sub, sublen - 1)
16
17
def combinations_from(map, length, k, acc, index, con, [lastix | ixsub], [_ | sub], sublen)
18
when index == length,
19
do: combinations_from(map, length, k, acc, lastix + 1, div(con, 10), ixsub, sub, sublen - 1)
20
21
def combinations_from(_map, length, _k, acc, index, _con, _ixsub, _sub, _sublen) when index == length,
22
do: acc
23
24
def combinations_from(map, length, k, acc, index, con, ixsub, sub, sublen) do
25
cond do
26
sublen == k - 1 ->
27
acc = max(acc, con*10 + map[index])
28
combinations_from(map, length, k, acc, index + 1, con, ixsub, sub, sublen)
29
(con * 10 + map[index] + 1) * (10 ** (k - sublen - 1)) >= acc ->
30
combinations_from(map, length, k, acc, index + 1, con * 10 + map[index], [index | ixsub], [map[index] | sub], sublen + 1)
31
true ->
32
combinations_from(map, length, k, acc, index + 1, con, ixsub, sub, sublen)
33
end
34
end
35
end
36
37
38
# input = """
39
# 987654321111111
40
# 811111111111119
41
# 234234234234278
42
# 818181911112111
43
# """
44
45
input = File.read!("3.input")
46
47
input
48
|> String.trim()
49
|> String.split("\n")
50
|> Task.async_stream(fn bank ->
51
bank
52
|> String.to_charlist()
53
|> Three.max_combination(12)
54
|> IO.inspect()
55
end, timeout: :infinity, max_concurrency: 8)
56
|> Enum.sum_by(fn {:ok, n} -> n end)
57
|> IO.inspect
58