@@ -25,7 +25,10 @@ from line in blocks[1].Split("\n")
25
25
p => new string [ ] { p . molecule [ 0 ] + p . element , p . element + p . molecule [ 1 ] }
26
26
) ;
27
27
28
- // cut the polymer into molecules, to get initial count:
28
+ // it's enough to maintain the molecule counts in each step, no
29
+ // need to deal with them one by one.
30
+
31
+ // cut the polymer into molecules first:
29
32
var moleculeCount = (
30
33
from i in Enumerable . Range ( 0 , polymer . Length - 1 )
31
34
@@ -48,12 +51,17 @@ group count by generatedMolecule into g
48
51
) . ToDictionary ( g => g . newMolecule , g => g . count ) ;
49
52
}
50
53
51
- // get occurrences by element, it's enough to take just one end of each molecule:
54
+ // now we need to switch to element counts, it's enough to take just one
55
+ // end of each molecule, so that we don't count elements twice.
52
56
var elementCounts = (
53
57
from kvp in moleculeCount
54
- group kvp . Value by kvp . Key [ 0 ] into g
58
+ let molecule = kvp . Key
59
+ let count = kvp . Value
60
+ let element = molecule [ 0 ] // take the start of the molecule
61
+ group count by element into g
55
62
select ( element : g . Key , count : g . Sum ( ) )
56
63
) . ToDictionary ( kvp => kvp . element , kvp => kvp . count ) ;
64
+
57
65
// but then, the count of the last element of the polymer is off by one:
58
66
elementCounts [ polymer . Last ( ) ] ++ ;
59
67
0 commit comments