Advertisement
Guest User

AoC24-2ab

a guest
Dec 2nd, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.13 KB | None | 0 0
  1. import Foundation
  2.  
  3. struct Report {
  4.   var levels: [Int]
  5.  
  6.   init(_ levels: [Int]) {
  7.     self.levels = levels
  8.   }
  9.  
  10.   func isSteady() -> Bool {
  11.     var steady: Bool
  12.     if levels == levels.sorted() || levels.reversed() == levels.sorted() {
  13.       steady = true
  14.     } else {
  15.       steady = false
  16.     }
  17.  
  18.     return steady
  19.   }
  20.  
  21.   func isGradual() -> Bool {
  22.     var gradual = true
  23.     for i in 0..<(levels.count-1) {
  24.       let check = abs(levels[i] - levels[i+1])
  25.       if (check < 1 || check > 3) {
  26.         gradual = false
  27.         break
  28.       }
  29.     }
  30.  
  31.     return gradual
  32.   }
  33. }
  34.  
  35. // Reads in and stores the input
  36. func getReports(from file: String) -> [Report] {
  37.   var input = (try? String(contentsOf: URL(fileURLWithPath: file)))!
  38.   if input[input.index(before: input.endIndex)] != "\n" {
  39.     input.append("\n")
  40.   }
  41.  
  42.   var reports = [Report]()
  43.  
  44.   var tempList = [Int](), tempEntry = ""
  45.   for c: Character in input {
  46.     if c >= "0" && c <= "9" {
  47.       tempEntry.append(c)
  48.     } else if c == " " && tempEntry != "" {
  49.       tempList.append(Int(tempEntry)!)
  50.       tempEntry = ""
  51.     } else if c == "\n" {
  52.       tempList.append(Int(tempEntry)!)
  53.       tempEntry = ""
  54.       reports.append(Report(tempList))
  55.       tempList.removeAll()
  56.     }
  57.   }
  58.  
  59.   return reports
  60. }
  61.  
  62. // Part 1 magic
  63. func getTotal1(of reports: [Report]) -> Int {
  64.   var total = 0
  65.   for r in reports {
  66.     total += (r.isSteady() && r.isGradual() ? 1 : 0)
  67.   }
  68.  
  69.   return total
  70. }
  71.  
  72. // Part 2 magic
  73. func getTotal2(of reports: [Report]) -> Int {
  74.   var total = 0
  75.   for r in reports {
  76.     var steady = r.isSteady(), gradual = r.isGradual()
  77.     if !steady || !gradual {
  78.       for i in 0..<r.levels.count {
  79.         var temp = r
  80.         temp.levels.remove(at: i)
  81.         if temp.isSteady() && temp.isGradual() {
  82.           steady = true
  83.           gradual = true
  84.         }
  85.       }
  86.     }
  87.     total += (steady && gradual ? 1 : 0)
  88.   }
  89.  
  90.   return total
  91. }
  92.  
  93. // int main()
  94. let reports = getReports(from: "input.txt")
  95.  
  96. let total1 = getTotal1(of: reports)
  97. print("Part 1 answer: \(total1)")
  98. let total2 = getTotal2(of: reports)
  99. print("Part 2 answer: \(total2)")
Tags: adventofcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement