Skip to content

Commit 09cd424

Browse files
committed
Attempt a more primitive variant
1 parent 3d66763 commit 09cd424

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

15.az.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

15.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func decode<S: StringProtocol>(_ s: S) -> Step {
4646
if splits.count == 1 {
4747
return Step(op: .remove(String(splits[0])), box: box)
4848
}
49-
let lens = Lens(label: splits[0], length: splits[1]);
49+
let lens = Lens(label: splits[0], length: splits[1])
5050
return Step(op: .replace(lens), box: box)
5151
}
5252

0 commit comments

Comments
 (0)