Created
December 13, 2017 00:19
-
-
Save TsuiAnthonYVR/d1f7294159feec03b919fc9c1acc3b17 to your computer and use it in GitHub Desktop.
Advent of Code Day 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import Foundation | |
let inputString: String = """ | |
pbga (66) | |
xhth (57) | |
ebii (61) | |
havc (66) | |
ktlj (57) | |
fwft (72) -> ktlj, cntj, xhth | |
qoyq (66) | |
padx (45) -> pbga, havc, qoyq | |
tknk (41) -> ugml, padx, fwft | |
jptl (61) | |
ugml (68) -> gyxo, ebii, jptl | |
gyxo (61) | |
cntj (57) | |
""" | |
var lines = inputString.split(separator: "\n") | |
let outerpattern = "([a-z]+) \\(([0-9]+)\\)(?: -> ((?:[a-z]+(?:, )?)+))?" | |
let re = try! NSRegularExpression(pattern: outerpattern) | |
struct Program { | |
var name : String | |
var children : [String] | |
var weight : Int | |
var parent : String? | |
} | |
var programs : [String : Program] = [:]; | |
var relationships : [String: [String]] = [:]; | |
for line in lines { | |
let range = NSMakeRange(0, line.count) | |
let matches = re.matches(in: String(line), options: NSRegularExpression.MatchingOptions(), range: range) | |
for match in matches { | |
var programName : String = "" | |
var weight : Int = 0 | |
var children : String = "" | |
for y in 0..<match.numberOfRanges { | |
if match.range(at: y).lowerBound > line.count { | |
continue; | |
} | |
let matchValue = ((line as NSString).substring(with: match.range(at: y))) | |
switch y { | |
case 1: | |
programName = matchValue | |
case 2: | |
if let weightInt = Int(matchValue) { | |
weight = weightInt | |
} else { | |
weight = 0 | |
} | |
case 3: | |
children = matchValue | |
default: | |
continue | |
} | |
} | |
let childrenArray = children.split(separator: ",").map({ | |
$0.trimmingCharacters(in: .whitespaces) | |
}) | |
programs[programName] = Program(name: programName, children: childrenArray, weight: weight, parent: nil) | |
} | |
} | |
for (name, parent) in programs { | |
for child in parent.children { | |
if var childProgram = programs[child] { | |
childProgram.parent = parent.name | |
programs[child] = childProgram | |
} | |
} | |
} | |
print ( | |
programs.filter ({ (name, program) -> Bool in | |
program.parent == nil | |
}).map({(name, program) -> String in name}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment