Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- "
- | Extensions to standard classes
- "
- Collection extend [
- apply: method [ ^self collect: [:x | x perform: method] ]
- ]
- OrderedCollection extend [
- " XXX: Quick implementation of multiple remove from front "
- removeFirst: num [
- | res |
- res := self first: num.
- num timesRepeat: [ self removeFirst ].
- ^res
- ]
- ]
- "
- | Class descriptions for cranes
- |
- | CrateMover9001 picks up crates all at once.
- | CrateMover9000 picks up one at a time, so they get reversed.
- |
- "
- Object subclass: CrateMover9001 [
- | stacks stackOrder |
- CrateMover9001 class >> new: stackText [
- ^super new init: stackText
- ]
- init: input [
- | stackPos |
- " Find stack pos in input: "
- stackPos := Dictionary new. " local for mapping pos in input "
- stacks := Dictionary new. " map of name -> stack "
- stackOrder := OrderedCollection new. " stacks in the order of the input "
- " Using last line as key, build maps and create stacks "
- (input lines last) keysAndValuesDo: [ :pos :name |
- (name ~= Character space) ifTrue: [
- stackPos at: pos put: name.
- stackOrder add: (stacks at: name put: OrderedCollection new)
- ]
- ].
- " Build stacks: "
- (input lines allButLast) do: [ :line |
- stackPos keysAndValuesDo: [ :pos :name |
- | crate |
- ((crate := line at: pos) isLetter) ifTrue: [
- (stacks at: name) add: crate
- ]
- ]
- ].
- ^self
- ]
- pickup: num from: src [
- ^(stacks at: src) removeFirst: num
- ]
- move: num from: src to: dst [
- (stacks at: dst) addAllFirst: (self pickup: num from: src)
- ]
- stackTops [
- ^String from: (stackOrder apply: #first)
- ]
- ]
- " Making 9000 the subclass, because it needs the extra work of reversing "
- CrateMover9001 subclass: CrateMover9000 [
- CrateMover9000 class >> new: stackText [
- ^super new: stackText
- ]
- pickup: num from: src [
- ^(super pickup: num from: src) reverse
- ]
- ]
- "
- | Mainline
- "
- section := stdin contents tokenize: '\n\n'.
- " First section is initial crate stacks, Init some cranes on them: "
- cranes := {CrateMover9000 new: section first. CrateMover9001 new: section first}.
- " Second section is the crane operations: "
- (section second lines) do: [ :cmd |
- | match |
- match := (cmd =~ 'move (\d+) from (.) to (.)') asArray.
- cranes do: [ :crane |
- crane move: (match first) asInteger
- from: (match second) first " only want first character "
- to: (match third) first " only want first character "
- ]
- ].
- cranes keysAndValuesDo: [ :i :crane |
- ('Part %1: %2' % {i. crane stackTops}) displayNl
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement