-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay02.swift
More file actions
93 lines (75 loc) · 2.15 KB
/
Day02.swift
File metadata and controls
93 lines (75 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import AOCCore
import Foundation
struct Day02: Day {
let title = "Gift Shop"
var rawInput: String?
func part1() throws -> Int {
input().raw
.split(separator: ",")
.map { $0.split(separator: "-") }
.compactMap { line -> ClosedRange<Int>? in
guard
let from = Int(line[0]),
let to = Int(line[1])
else { return nil }
return from...to
}
.reduce(into: 0) { result, range in
for i in range where i.isTwiceSequenceOfDigits() {
result += i
}
}
}
func part2() throws -> Int {
input().raw
.split(separator: ",")
.map { $0.split(separator: "-") }
.compactMap { line -> ClosedRange<Int>? in
guard
let from = Int(line[0]),
let to = Int(line[1])
else { return nil }
return from...to
}
.reduce(into: 0) { result, range in
for i in range where i.isMultipleSequenceOfDigits() {
result += i
}
}
}
}
private extension Int {
func isTwiceSequenceOfDigits() -> Bool {
let n = countOfDigits
guard
n.isEven
else { return false }
let base = pow10(n / 2)
let left = self / base
let right = self % base
return left == right
}
func isMultipleSequenceOfDigits() -> Bool {
let n = countOfDigits
guard
n > 1
else { return false }
for size in 1...(n / 2) where n.isMultiple(of: size) {
var match = true
let base = pow10(size)
let pattern = self % base
var value = self / base
while value > 0 {
if value % base != pattern {
match = false
break
}
value /= base
}
if match {
return true
}
}
return false
}
}