-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5_2.groovy
62 lines (57 loc) · 1.44 KB
/
day5_2.groovy
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
def sampleInput = '''47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47
'''
static List<Integer> sort(Map<Integer, List<Integer>> conditions, List<Integer> update) {
def newUpdate = []
int n = update.size()
for(int i = 0; i < n; i++) {
// find an element that has no predecessor in the list
def element = update.find {candidate -> update.every { !conditions[it]?.contains(candidate)} }
newUpdate << element
update.removeElement(element)
}
newUpdate
}
static long solve(List<String> input) {
int divider = input.findIndexOf { it.isEmpty() }
def conditions = input.take(divider).collect {it.split(/\|/).collect { it as int} }.groupBy { it[0] }.collectEntries {k,v -> [k, v.collect {it[1] } ] }
def updates = input.drop(divider+1).collect { it.split(',').collect { it as int } }
updates.findAll { update ->
update.withIndex().any { element, index ->
((index+1)..<(update.size())).any { i ->
(conditions[update[i]])?.contains(element)
}
}
} .collect {
sort(conditions, it) }
.collect {
it[(it.size()-1)/2 as int] }
.sum() as long ?: 0
}
assert 123L == solve(sampleInput.split('\n') as List)
println solve(new File('input/day5.txt').readLines())