Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- struct Report {
- var levels: [Int]
- init(_ levels: [Int]) {
- self.levels = levels
- }
- func isSteady() -> Bool {
- var steady: Bool
- if levels == levels.sorted() || levels.reversed() == levels.sorted() {
- steady = true
- } else {
- steady = false
- }
- return steady
- }
- func isGradual() -> Bool {
- var gradual = true
- for i in 0..<(levels.count-1) {
- let check = abs(levels[i] - levels[i+1])
- if (check < 1 || check > 3) {
- gradual = false
- break
- }
- }
- return gradual
- }
- }
- // Reads in and stores the input
- func getReports(from file: String) -> [Report] {
- var input = (try? String(contentsOf: URL(fileURLWithPath: file)))!
- if input[input.index(before: input.endIndex)] != "\n" {
- input.append("\n")
- }
- var reports = [Report]()
- var tempList = [Int](), tempEntry = ""
- for c: Character in input {
- if c >= "0" && c <= "9" {
- tempEntry.append(c)
- } else if c == " " && tempEntry != "" {
- tempList.append(Int(tempEntry)!)
- tempEntry = ""
- } else if c == "\n" {
- tempList.append(Int(tempEntry)!)
- tempEntry = ""
- reports.append(Report(tempList))
- tempList.removeAll()
- }
- }
- return reports
- }
- // Part 1 magic
- func getTotal1(of reports: [Report]) -> Int {
- var total = 0
- for r in reports {
- total += (r.isSteady() && r.isGradual() ? 1 : 0)
- }
- return total
- }
- // Part 2 magic
- func getTotal2(of reports: [Report]) -> Int {
- var total = 0
- for r in reports {
- var steady = r.isSteady(), gradual = r.isGradual()
- if !steady || !gradual {
- for i in 0..<r.levels.count {
- var temp = r
- temp.levels.remove(at: i)
- if temp.isSteady() && temp.isGradual() {
- steady = true
- gradual = true
- }
- }
- }
- total += (steady && gradual ? 1 : 0)
- }
- return total
- }
- // int main()
- let reports = getReports(from: "input.txt")
- let total1 = getTotal1(of: reports)
- print("Part 1 answer: \(total1)")
- let total2 = getTotal2(of: reports)
- print("Part 2 answer: \(total2)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement