Skip to content

Commit 4b8438c

Browse files
Solve day07 part 2 and generalize CrabAlignment struct
1 parent 7e8f5b7 commit 4b8438c

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

2021.playground/Pages/Day07.xcplaygroundpage/Contents.swift

+32-9
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,55 @@ struct CrabAlignment {
77
var position: Int
88
var horizontalPositions: [Int]
99

10-
init(for position: Int, horizontalPositions: [Int]) {
10+
init(for position: Int, horizontalPositions: [Int], constantRate: Bool) {
1111
self.position = position
1212
self.horizontalPositions = horizontalPositions
13-
var total = 0
14-
for curr_pos in horizontalPositions {
15-
total += abs(curr_pos - position)
13+
var total: Int = 0
14+
if constantRate {
15+
for curr_pos in horizontalPositions {
16+
total += abs(curr_pos - position)
17+
}
18+
} else {
19+
for curr_pos in horizontalPositions {
20+
total += ( ( abs(curr_pos - position) * (abs(curr_pos - position) + 1) ) / 2 )
21+
}
1622
}
1723
self.totalFuel = total
1824
}
1925
}
2026

2127
func partOne() -> String {
2228
// load input and remove \n
23-
let input = load(file: "input07_test", ofType: .txt)?.replacingOccurrences(of: "\n", with: "")
29+
let input = load(file: "input07", ofType: .txt)?.replacingOccurrences(of: "\n", with: "")
2430
// turn numbers in [Int]
2531
let horizontalPositions = input?.split(separator: ",").map { Int($0)! }
2632

2733
var crabAlignmentArray: [CrabAlignment] = []
28-
for align_pos in horizontalPositions! {
29-
crabAlignmentArray.append(CrabAlignment(for: align_pos, horizontalPositions: horizontalPositions!))
34+
// Crabs can be aligned at any horizontal position
35+
for align_pos in horizontalPositions!.min()! ... horizontalPositions!.max()! {
36+
crabAlignmentArray.append(CrabAlignment(for: align_pos, horizontalPositions: horizontalPositions!, constantRate: true))
3037
}
31-
// sort
38+
// sort array for the least total fuel
3239
crabAlignmentArray.sort { $0.totalFuel < $1.totalFuel }
3340
return crabAlignmentArray[0].totalFuel.description
3441
}
3542

36-
print(partOne())
43+
func partTwo() -> String {
44+
// load input and remove \n
45+
let input = load(file: "input07", ofType: .txt)?.replacingOccurrences(of: "\n", with: "")
46+
// turn numbers in [Int]
47+
let horizontalPositions = input?.split(separator: ",").map { Int($0)! }
48+
49+
var crabAlignmentArray: [CrabAlignment] = []
50+
// Crabs can be aligned at any horizontal position
51+
for align_pos in horizontalPositions!.min()! ... horizontalPositions!.max()! {
52+
crabAlignmentArray.append(CrabAlignment(for: align_pos, horizontalPositions: horizontalPositions!, constantRate: false))
53+
}
54+
// sort array for the least total fuel
55+
crabAlignmentArray.sort { $0.totalFuel < $1.totalFuel }
56+
return crabAlignmentArray[0].totalFuel.description
57+
}
3758

59+
print(partOne())
60+
print(partTwo())
3861
//: [Next](@next)

0 commit comments

Comments
 (0)