Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active December 18, 2017 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/5bc7a20d109d44976508331b8a659bd6 to your computer and use it in GitHub Desktop.
Save JadenGeller/5bc7a20d109d44976508331b8a659bd6 to your computer and use it in GitHub Desktop.
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