File tree 2 files changed +45
-1
lines changed
2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change
1
+ var s = 0
2
+ var boxes : [ [ [ String ] ] ] = Array ( repeating: [ ] , count: 256 )
3
+ while let line = readLine ( ) {
4
+ for word in line. split ( separator: " , " ) {
5
+ let splits = word. split { $0 == " = " || $0 == " - " } . map { String ( $0) }
6
+ let bi = hash ( splits [ 0 ] )
7
+ s += hash ( String ( word) )
8
+ boxes [ bi] = modify ( box: boxes [ bi] , splits, bi)
9
+ }
10
+ }
11
+ print ( s, power ( boxes) )
12
+
13
+ func hash( _ s: String ) -> Int {
14
+ return s. utf8. reduce ( 0 ) { ( $0 + Int( $1) ) * 17 % 256 }
15
+ }
16
+
17
+ func modify( box: [ [ String ] ] , _ splits: [ String ] , _ bi: Int ) -> [ [ String ] ] {
18
+ var box = box
19
+ var label = splits. first
20
+ if splits. count == 1 {
21
+ box. removeAll { $0. first == label }
22
+ } else {
23
+ for (i, l) in box. enumerated ( ) {
24
+ if l. first == label {
25
+ box [ i] = splits
26
+ label = nil
27
+ }
28
+ }
29
+ if let _ = label {
30
+ box. append ( splits)
31
+ }
32
+ }
33
+ return box
34
+ }
35
+
36
+ func power( _ boxes: [ [ [ String ] ] ] ) -> Int {
37
+ var s = 0
38
+ for (i, box) in boxes. enumerated ( ) {
39
+ for (j, lens) in box. enumerated ( ) {
40
+ s += ( i + 1 ) * ( j + 1 ) * Int( lens. last!, radix: 10 ) !
41
+ }
42
+ }
43
+ return s
44
+ }
Original file line number Diff line number Diff line change @@ -46,7 +46,7 @@ func decode<S: StringProtocol>(_ s: S) -> Step {
46
46
if splits. count == 1 {
47
47
return Step ( op: . remove( String ( splits [ 0 ] ) ) , box: box)
48
48
}
49
- let lens = Lens ( label: splits [ 0 ] , length: splits [ 1 ] ) ;
49
+ let lens = Lens ( label: splits [ 0 ] , length: splits [ 1 ] )
50
50
return Step ( op: . replace( lens) , box: box)
51
51
}
52
52
You can’t perform that action at this time.
0 commit comments