Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Collection extend [
- product [ ^self inject: 1 into: [:a :b | a * b] ]
- ]
- "
- | XXX: Not robust or complete, so play nice. Doing this because even though Bag exists,
- | it doesn't have Set operations. Bag also doesn't have great functionality for
- | extending to do these... most notably is the lack of being able to remove multiple
- | of an item. So, Dictionary it is.
- |
- | Note there's noting preventing negative amounts of items. Or zero being stored and
- | making isEmpty fail. We do handle these with the difference operator, so isEmpty
- | is safe after that.
- "
- Dictionary subclass: MultiSet [
- <shape: #pointer>
- " Union of self with aMultiSet "
- + aMultiSet [
- ^MultiSet from: ((aMultiSet keys + self keys) collect: [ :key |
- key -> ((aMultiSet at: key ifAbsent: [0])
- max: (self at: key ifAbsent: [0])).
- ]).
- ]
- " Difference of self with aMultiSet "
- - aMultiSet [
- ^MultiSet from: (self keys collect: [ :key |
- | diff |
- diff := (self at: key ifAbsent: [0]) - (aMultiSet at: key ifAbsent: [0]).
- (diff > 0) ifTrue: [ key -> diff ].
- ]).
- ]
- ]
- " Number of cubes we're testing for: "
- want := MultiSet from: {#red -> 12. #green -> 13. #blue -> 14}.
- part1 := 0.
- part2 := 0.
- stdin linesDo: [ :line |
- sections := line subStrings: ':'.
- game := sections first subStrings last asNumber. " Game num:"
- draws := (sections second subStrings: ',;') collect: [ :draw |
- | pair |
- pair := draw subStrings. " num colour"
- pair second asSymbol -> pair first asNumber
- ].
- " Get max seen for each colour of cube by unioning draws together. "
- maxSeen := draws inject: (MultiSet new) into: [:a :draw | a + (MultiSet from: {draw})].
- " We want to see nothing more (including puce cubes) than what we want. "
- (maxSeen - want) isEmpty ifTrue: [
- part1 := part1 + game.
- ].
- part2 := part2 + maxSeen values product.
- ].
- ('Part 1: %1' % {part1}) displayNl.
- ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement