Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Tree : NSObject {
- var nodes:[Node] = [Node]()
- func output(){
- let parents = nodes.filter{ $0.isParent }
- parents.first?.output()
- }
- func addRelationship(_ rel:String) {
- var ids:[String] = rel.components(separatedBy: ",")
- let parentNode = getNode(withID: ids[0])
- parentNode.isParent = true
- for i in 1 ..< ids.count{
- let child:Node = getNode(withID: ids[i])
- child.isParent = false
- parentNode.children.append(child)
- }
- }
- func getNode( withID id:String ) -> Node{
- let ref : [Node] = nodes.filter{ id == $0.id }
- if ref.count > 0 {
- return ref.first!
- }
- let node = Node(withId: id)
- nodes.append(node)
- return node
- }
- }
- class Node:NSObject {
- let id:String
- var isParent:Bool = false
- var children:[Node] = [Node]()
- init ( withId id:String ){
- self.id = id
- }
- func output(order : Int = 0) {
- var desc = (0...order).map{_ in " "}.joined() + id
- print(desc)
- for i in children {
- i.output(order: order + 1)
- }
- }
- }
- let input:[String] = ["B2,E5,F6", "A1,B2,C3,D4", "D4,G7,I9", "G7,H8"]
- let organizations:Tree = Tree()
- _ = input.map{ organizations.addRelationship($0) }
- organizations.output()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement