re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

Hmm... I just took the input and stuck it in an array rather than reading it from disk. That's not hard to do in Swift though, maybe I'll go back and add in the file loading.

In any case, here is what I did in my Playground!

Swift

Part 1

This one was super easy in Swift via it's reduce(_:_:) function. Given that I had the Ints in an Array, it was a one liner. I added some context to the output because why not?

print("The final calculated frequency is: \(frequencyInput.reduce(0,+))")

For those of you new to Swift, this version of reduce has two inputs. The first one is the starting value for the accumulator and the second is the closure of what to do with the values from the collection. This is simply a shorthand syntax for adding all the values in a collection together and returning it. The long version looks like this:

let frequency = frequencyInput.reduce(0, { x, y in
    x + y
})
Part 2

This part was a bit tougher and my first attempt had all kinds of bad smells like breaking to function labels and such. Eventually I wrapped it all up in a closure that takes an Array of Int values and then returns a single Int with the first repeated number.

/// A closure that takes an `Array` of `Int` values and adds them together in a loop. Upon finding the first repeated
/// value it breaks and returns.
let findRepeatedFrequency = {(_ inputArray: [Int]) -> Int in
    var accumilated = 0
    var frequencies = Set<Int>()
    while true {
        for skew in inputArray {
            accumilated += skew
            if frequencies.contains(accumilated) {
                return accumilated
            }
            frequencies.insert(accumilated)
        }
    }
}

print("The first repeated frequency is: \(findRepeatedFrequency(frequencyInput))")

Essentially this is a for-loop version of the reduce operation, but then I also maintain a history of the values in a Set and check to see if this is a value we've run into before.

I solved the second one with a closure instead of a regular function because I've been teaching myself more about them lately.

 

Thanks! The explanations are really interesting too!

code of conduct - report abuse