Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Collection extend [
- apply: method [ ^self collect: [:x | x perform: method] ]
- sum [ ^self fold: [:a :b | a + b] ]
- " Calculate total fuel to get to val, using weight block "
- getFuel: val weight: block [
- ^self inject: 0 into: [ :acc :x |
- acc + (block value: val value: x)
- ]
- ]
- ]
- Integer extend [
- " Extension to calculate triangular numbers "
- triangle [ ^(self * (self + 1)) / 2 ]
- ]
- "
- | Mainline
- "
- input := ((stdin nextLine substrings: $,) apply: #asNumber) sorted.
- " Part 1 is at median. If list is even it has two medians, but all values
- | between them will give the same result by symmetry as moving from one to
- | the other involves adding fuel for half on one side and subtracting the
- | same amount from the other half. "
- median := input at: input size // 2.
- part1 := input getFuel: median weight: [:x :y | (x - y) abs].
- ('Part 1: %1' % {part1}) displayNl.
- " Part 2 is around the mean. The mean is almost certainly not an integer,
- | which is what we want. So take the minimum of the integers on either side of it. "
- mean := input sum // input size.
- part2 := {mean. mean + 1} inject: SmallInteger largest into: [ :acc :mean |
- acc min: (input getFuel: mean weight: [:x :y | (x - y) abs triangle])
- ].
- ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement