Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 9, 2020 05:56
Show Gist options
  • Save felix-larsen/7a67749983ef0b5c26a5d5f8ade7a919 to your computer and use it in GitHub Desktop.
Save felix-larsen/7a67749983ef0b5c26a5d5f8ade7a919 to your computer and use it in GitHub Desktop.
9th December solution - Advent of Code - swift
let preamble = 25
var solution1 = -1
for i in 0..<numbers.count {
if !checkThatAnyNumbers(in: Array(numbers[i..<preamble + i]), sumTo: numbers[preamble + i]) {
solution1 = numbers[preamble + i]
break
}
}
print(solution1)
func checkThatAnyNumbers(in numbers: [Int], sumTo sum: Int) -> Bool{
for indexNum1 in 0..<numbers.count {
for indexNum2 in (indexNum1 + 1)..<numbers.count {
if numbers[indexNum1] + numbers[indexNum2] == sum {
return true
}
}
}
return false
}
let newSum = solution1
var solution2 = [Int]()
outerLoop: for i in 0..<numbers.count {
innerLoop: for i2 in (i + 1)..<numbers.count {
let sum = numbers[i...i2].reduce(0, +)
if sum > newSum {
break innerLoop
} else if sum == newSum {
solution2 = Array(numbers[i...i2])
break outerLoop
}
}
}
print(solution2.min()! + solution2.max()!)
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december09.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines)
let numbers = lines.compactMap { Int($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment