Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Object subclass: Game [
- | deck1 deck2 states |
- Game class >> deck1: d1 deck2: d2 [
- ^(super new) deck1: d1 deck2:d2.
- ]
- deck1: d1 deck2: d2 [
- deck1 := d1.
- deck2 := d2.
- states := LookupTable new.
- ^self.
- ]
- make_hash [
- ^(String join: deck1 separatedBy: ','), ':', (String join: deck2 separatedBy: ',').
- ]
- test_loop [
- | hash |
- hash := self make_hash.
- (states keys includes: hash) ifTrue: [ ^true ].
- states at: hash put: 1.
- ^false.
- ]
- score [
- | win_deck score |
- score := 0.
- win_deck := (deck1 size > 0) ifTrue: [ deck1 ] ifFalse: [deck2 ].
- win_deck := win_deck collect: [ :c | c asNumber ].
- win_deck reverse keysAndValuesDo: [ :i :v | score := score + (i * v) ].
- ^score.
- ]
- play [
- | curr_state win_hand card1 card2 sub new1 new2 |
- stdout nextPutAll: '.'; flush.
- [(deck1 size > 0) and: [deck2 size > 0]] whileTrue: [
- (self test_loop) ifTrue: [ ^1 ]. " Player 1 wins infinite games "
- card1 := deck1 removeFirst asNumber.
- card2 := deck2 removeFirst asNumber.
- ((card1 <= deck1 size) and: [card2 <= deck2 size]) ifTrue: [
- " Recurse into subgame "
- new1 := deck1 copyFrom: 1 to: card1.
- new2 := deck2 copyFrom: 1 to: card2.
- sub := Game deck1: new1 deck2: new2.
- win_hand := sub play.
- ] ifFalse: [
- win_hand := (card1 > card2) ifTrue: [1] ifFalse: [2].
- ].
- (win_hand = 1) ifTrue: [
- deck1 addLast: card1 asString; addLast: card2 asString.
- ] ifFalse: [
- deck2 addLast: card2 asString; addLast: card1 asString.
- ].
- ].
- ^(deck1 size > 0) ifTrue: [1] ifFalse: [2].
- ]
- ]
- "
- | Mainline
- "
- " Read decks "
- section := stdin contents tokenize: '\n\n'.
- deck1 := ((section first) tokenize: '\n') asOrderedCollection removeFirst; yourself.
- deck2 := ((section second) tokenize: '\n') asOrderedCollection removeFirst; yourself.
- " Play game "
- game := Game deck1: deck1 deck2: deck2.
- stdout nextPutAll: 'Winner: ', game play asString; nl.
- stdout nextPutAll: 'Part 1: ', game score asString; nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement