@@ -7,32 +7,55 @@ struct CrabAlignment {
7
7
var position : Int
8
8
var horizontalPositions : [ Int ]
9
9
10
- init ( for position: Int , horizontalPositions: [ Int ] ) {
10
+ init ( for position: Int , horizontalPositions: [ Int ] , constantRate : Bool ) {
11
11
self . position = position
12
12
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
+ }
16
22
}
17
23
self . totalFuel = total
18
24
}
19
25
}
20
26
21
27
func partOne( ) -> String {
22
28
// 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: " " )
24
30
// turn numbers in [Int]
25
31
let horizontalPositions = input? . split ( separator: " , " ) . map { Int ( $0) ! }
26
32
27
33
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 ) )
30
37
}
31
- // sort
38
+ // sort array for the least total fuel
32
39
crabAlignmentArray. sort { $0. totalFuel < $1. totalFuel }
33
40
return crabAlignmentArray [ 0 ] . totalFuel. description
34
41
}
35
42
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
+ }
37
58
59
+ print ( partOne ( ) )
60
+ print ( partTwo ( ) )
38
61
//: [Next](@next)
0 commit comments