Untitled

mail@pastecode.io avatar
unknown
swift
2 years ago
2.6 kB
2
Indexable
Never
public func day13() {
    
    enum ComparisonResult {
        case less, equal, greater
    }
    func c(_ l:Int, _ r:Int) -> ComparisonResult{
        if l < r {
            return ComparisonResult.less
        }else if l > r {
            return ComparisonResult.greater
        }
        return ComparisonResult.equal
    }
    func compare(_ lhs: Any, _ rhs: Any) -> ComparisonResult {
        if let leftInt = lhs as? Int, let rightInt = rhs as? Int {
            return c(leftInt, rightInt)
        }
        
        if let leftList = lhs as? [Any], let rightList = rhs as? [Any] {
            let minLength = min(leftList.count, rightList.count)
            for i in 0..<minLength {
                let leftElement = leftList[i]
                let rightElement = rightList[i]
                let result = compare( leftElement, rightElement)
                if result != ComparisonResult.equal {
                    return result
                }
            }
            return c(leftList.count, rightList.count)
        }
        
        if let leftInt = lhs as? Int {
            return compare( [leftInt], rhs)
        }
        if let rightInt = rhs as? Int {
            return compare(lhs, [rightInt])
        }
        return ComparisonResult.equal
    }
    let fileURL = Bundle.main.url(forResource: "day13", withExtension: "txt")
    let groups = try! String(contentsOf: fileURL!, encoding: String.Encoding.utf8).components(separatedBy: "\n\n").filter{!$0.isEmpty}
    var sum = 0
    var allPackets : [Any] = []
    var allPacketStrings : [String] = []
    for (i, group) in groups.enumerated() {
        let parsedStrings = group.components(separatedBy: "\n").filter{!$0.isEmpty}
        let parsed = parsedStrings.map{  try! JSONSerialization.jsonObject(with: $0.data(using: .utf8)!, options: []) as! [Any]  }
        
        allPackets.append(contentsOf: parsed)
        allPacketStrings.append(contentsOf: parsedStrings)
        
        if compare(parsed[0], parsed[1]) != ComparisonResult.greater {
            print(i)
            sum += i+1
        }
    }

    print("Sum \(sum)")
    let dividerPackets : [Any] = [[[2]], [[6]]]
    let dividerStrings = ["[[[2]]", "[[6]]]"]
    allPackets.append(contentsOf: dividerPackets)
    allPacketStrings.append(contentsOf:dividerStrings)
    
    let sorted = allPackets.enumerated().sorted { compare($0.1, $1.1) == ComparisonResult.less }
    
    var key = 1
    sorted.map(\.0).enumerated().forEach{
        let s = allPacketStrings[$0.1]
        if (dividerStrings.contains(s)) {
            key *= ($0.0 + 1)
        }
    }
    
    print(key)
}