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] ]
- ]
- LookupTable extend [
- reverseMap [
- ^self associations inject: LookupTable new into: [ :acc :map |
- (acc at: map value ifAbsentPut: [Set new]) add: map key.
- acc
- ]
- ]
- ]
- "
- | Mainline
- "
- " Table mapping the lights to the digit they produce: "
- digits := LookupTable from: {
- 'abcefg' -> $0.
- 'cf' -> $1.
- 'acdeg' -> $2.
- 'acdfg' -> $3.
- 'bcdf' -> $4.
- 'abdfg' -> $5.
- 'abdefg' -> $6.
- 'acf' -> $7.
- 'abcdefg' -> $8.
- 'abcdfg' -> $9.
- }.
- part1 := 0.
- part2 := 0.
- stdin linesDo: [ :line |
- sections := (line substrings: $|) collect: [:pat | pat substrings apply: #asSet ].
- "
- | Part 1:
- "
- part1 := part1 + (sections second count: [:s | (s size between: 5 and: 6) not]).
- "
- | Part 2:
- "
- " Make table of number of occurences in signal -> Set of letters "
- sigCounts := (sections first inject: Bag new into: [ :acc :sig |
- acc addAll: sig; yourself
- ]) contents reverseMap.
- " Make table of size of signals -> Set of those signals (Set of letters)"
- sigLens := (LookupTable from: (sections first collect: [ :sig |
- sig -> sig size
- ])) reverseMap.
- " The unique signal lengths "
- one := (sigLens at: 2) anyOne.
- seven := (sigLens at: 3) anyOne.
- four := (sigLens at: 4) anyOne.
- eight := (sigLens at: 7) anyOne.
- " Building mapping: "
- mapping := LookupTable new.
- " The unique of lights in all ten digits "
- mapping at: $e put: (sigCounts at: 4).
- mapping at: $b put: (sigCounts at: 6).
- mapping at: $f put: (sigCounts at: 9).
- " Some set arithmetic to work out the remaining four "
- mapping at: $c put: (one - (mapping at: $f)).
- mapping at: $a put: (seven - one).
- mapping at: $g put: (eight - four - (mapping at: $a) - (mapping at: $e)).
- " Final value calculated by exclusion of all others from 8 "
- mapping at: $d put: (mapping values inject: eight into: [:acc :val | acc - val]).
- " Flatten and reverse the map "
- mapping := (mapping apply: #anyOne) reverseMap apply: #anyOne.
- " Apply mapping, get digits from table, convert to number "
- output := (sections second collect: [ :sig |
- digits at: (sig collect: [:let | mapping at: let]) asString sorted
- ]) asString asNumber.
- part2 := part2 + output.
- ].
- ('Part 1: %1' % {part1}) displayNl.
- ('Part 2: %1' % {part2}) displayNl.
Add Comment
Please, Sign In to add comment