day 16 in swift - its slow but got answer though
extension Collection where Index: Comparable { subscript(back i: Int) -> Iterator.Element { let backBy = i + 1 return self[self.index(self.endIndex, offsetBy: -backBy)] } } extension Array { init(repeating: [Element], count: Int) { self.init([[Element]](repeating: repeating, count: count).flatMap{$0}) } func repeated(count: Int) -> [Element] { return [Element](repeating: self, count: count) } } extension BinaryInteger { var digits: [Int] { return String(describing: self).compactMap { Int(String($0)) } } } func fft(_ input: [Int]) -> [Int] { var next:[Int] = Array.init(repeating: 0, count: input.count) var list: [Int] = input list.insert(0, at: 0) let pattern:[Int:Int] = [0:0, 1:1,2:0,3:-1] for i in (0 ..< input.count) { for j in (0 ..< list.count) { let value = (j / (i + 1)) % 4 let y = pattern[value]! let x = list[j] next[i] += x * y } } next = next.map{ $0.digits.last! } // print(next) return next } func fft2(_ input: [Int]) -> [Int] { var next:[Int] = Array.init(repeating: 0, count: input.count) var ans = 0 for i in (1 ... input.count/2) { ans += input[back: i] let index = next.index(next.endIndex, offsetBy: -(i+1)) next[index] = ans } next = next.map{ abs($0)%10 } return next } func partOne() { var output: [Int] = input for a in (1 ... 100) { print("Processing \(a)") output = fft(output) print("ouput \(output[0...7])") } print("Part 1 answer is : \(output[0 ... 7])") } func partTwo() { var output: Array<Int> = Array.init(repeating: input, count: 10000) var offString = "" let array = output[0...6] _ = array.map{ a in offString = offString + "\(a)" } let offset = Int(offString)! for a in (1...100) { print("Processing \(a)") output = fft2(output) print("ouput \(output[0...7])") } print("Part 2 answer is : \(output[offset ... offset+7])") } partOne() partTwo()
We're a place where coders share, stay up-to-date and grow their careers.
day 16 in swift - its slow but got answer though