-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.nim
67 lines (56 loc) · 1.41 KB
/
solution.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import std/[
algorithm,
bitops,
deques,
json,
math,
re,
sequtils,
sets,
strformat,
strutils,
tables,
sugar,
]
proc take(w: seq[int], target: int): seq[seq[int]] =
var res = newSeq[seq[int]]()
var minLen = int.high
proc search(i, target: int, partial: seq[int]) =
if target == 0:
if minLen > partial.len:
minLen = partial.len
res = @[partial]
elif minLen == partial.len:
res.add partial
return
if i >= w.len or target < 0 or partial.len > minLen: return
search(i + 1, target - w[i], partial & w[i])
search(i + 1, target, partial)
search(0, target, @[])
res
when defined(test):
block:
let w = (1 .. 5).toSeq & (7 .. 11).toSeq
doAssert take(w, w.sum div 3) == @[@[9,11]]
proc calc(w: seq[int]): int =
take(w, w.sum div 3).mapIt(it.foldl a * b).min
when defined(test):
block:
let w = (1 .. 5).toSeq & (7 .. 11).toSeq
doAssert calc(w) == 99
proc part1(input: string): int =
let w = input.split("\n").mapIt(it.parseInt)
calc(w)
proc calc2(w: seq[int]): int =
take(w, w.sum div 4).mapIt(it.foldl a * b).min
when defined(test):
block:
let w = (1 .. 5).toSeq & (7 .. 11).toSeq
doAssert calc2(w) == 44
proc part2(input: string): int =
let w = input.split("\n").mapIt(it.parseInt)
calc2(w)
when isMainModule and not defined(test):
let input = readAll(stdin).strip
echo part1(input)
echo part2(input)