-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc2024_day_22.swift
112 lines (85 loc) · 2.48 KB
/
aoc2024_day_22.swift
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import Foundation
import UIKit
import HeapModule
class ViewController: UIViewController {
let input =
"""
"""
let testInput =
"""
1
2
3
2024
"""
private typealias PriceChange = (price: Int, change: Int)
override func viewDidLoad() {
super.viewDidLoad()
parse()
part1()
part2()
}
var numbers: [Int] = []
func parse() {
numbers = testInput.split(separator: "\n")
// numbers = input.split(separator: "\n")
.map({ Int(String($0)) ?? 0 })
}
func nextSecretNumber(number: Int) -> Int {
var number = number
let mul64 = number * 64
let mix1 = mul64 ^ number
number = mix1
let prune1 = mix1 % 16777216
number = prune1
let div32 = number / 32
let mix2 = div32 ^ number
number = mix2
let prune2 = mix2 % 16777216
number = prune2
let mul2048 = prune2 * 2048
let mix3 = mul2048 ^ number
number = mix3
let prune3 = mix3 % 16777216
return prune3
}
func secretNumber(initialNumber: Int, n: Int) -> Int {
var number = initialNumber
for _ in 0..<n {
let nextNumber = nextSecretNumber(number: number)
number = nextNumber
}
return number
}
func secretNumbers(initialNumber: Int, n: Int) -> [Int] {
var number = initialNumber
var result: [Int] = []
for _ in 0..<n {
let nextNumber = nextSecretNumber(number: number)
result.append(nextNumber)
number = nextNumber
}
return result
}
func part1() {
var sum = 0
for number in numbers {
let result = secretNumber(initialNumber: number, n: 2000)
sum += result
}
print(sum)
}
func part2() {
let offers = numbers.map { n in
let prices = secretNumbers(initialNumber: n, n: 2000).map { $0 % 10 }
let changes = zip(prices, prices[1...]).map { $1 - $0 }
let changesPricePairs = prices[4...].enumerated().map { i, price in
(changes[i...(i + 3)].map { String($0) }.joined(), price)
}
return Dictionary(changesPricePairs, uniquingKeysWith: { first, _ in first } )
}
let allOffers = offers.reduce([:]) { $0.merging($1, uniquingKeysWith: +) }
let bestOffer = allOffers.values.max() ?? 0
print(bestOffer)
}
}