Skip to content

Instantly share code, notes, and snippets.

@JadenGeller JadenGeller/Advent1.swift
Last active Dec 18, 2017

Embed
What would you like to do?
Advent Day 1
public struct RotatingIterator<Base: IteratorProtocol>: Sequence, IteratorProtocol {
private var skippedElements: [Base.Element] = []
private var base: Base
internal init(_ base: Base, count: Int) {
self.base = base
for _ in 0..<count {
guard let element = self.base.next() else { break }
self.skippedElements.append(element)
}
}
public mutating func next() -> Base.Element? {
if let element = base.next() { return element }
// FIXME: Swift compiler bug prevents this from working.
// return skippedElements.popFirst()
return skippedElements.isEmpty ? nil : skippedElements.removeFirst()
}
}
extension Sequence {
public func rotating(by count: Int) -> RotatingIterator<Iterator> {
return RotatingIterator(makeIterator(), count: count)
}
}
func captcha1<S: Sequence>(_ input: S) -> S.Iterator.Element where S.Iterator.Element: Numeric {
return zip(input, input.rotating(by: 1)).lazy.filter({ $0.0 == $0.1 }).map({ $0.0 }).reduce(0, +)
}
func captcha2<Element>(_ input: [Element]) -> Element where Element: Numeric {
precondition(input.count % 2 == 0)
return zip(input, input.rotating(by: input.count / 2)).lazy.filter({ $0.0 == $0.1 }).map({ $0.0 }).reduce(0, +)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.