Advertisement
phantomon

Sample Tree

Dec 15th, 2017
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.41 KB | None | 0 0
  1. class Tree : NSObject {
  2.     var nodes:[Node] = [Node]()
  3.    
  4.     func output(){
  5.         let parents = nodes.filter{ $0.isParent }
  6.        
  7.         parents.first?.output()
  8.     }
  9.    
  10.     func addRelationship(_ rel:String) {
  11.         var ids:[String] = rel.components(separatedBy: ",")
  12.        
  13.         let parentNode = getNode(withID: ids[0])
  14.         parentNode.isParent = true
  15.         for i in 1 ..< ids.count{
  16.             let child:Node = getNode(withID: ids[i])
  17.             child.isParent = false
  18.             parentNode.children.append(child)
  19.            
  20.         }
  21.     }
  22.    
  23.     func getNode( withID id:String ) -> Node{
  24.         let ref : [Node] = nodes.filter{ id == $0.id }
  25.         if ref.count > 0 {
  26.             return ref.first!
  27.         }
  28.         let node = Node(withId: id)
  29.         nodes.append(node)
  30.         return node
  31.     }
  32. }
  33.  
  34. class Node:NSObject {
  35.     let id:String
  36.     var isParent:Bool = false
  37.     var children:[Node] = [Node]()
  38.    
  39.     init ( withId id:String ){
  40.         self.id = id
  41.     }
  42.    
  43.     func output(order : Int = 0) {
  44.         var desc = (0...order).map{_ in "   "}.joined() + id
  45.         print(desc)
  46.         for i in children {
  47.             i.output(order: order + 1)
  48.         }
  49.     }
  50. }
  51.  
  52. let input:[String] = ["B2,E5,F6", "A1,B2,C3,D4", "D4,G7,I9", "G7,H8"]
  53. let organizations:Tree = Tree()
  54.  
  55. _ = input.map{ organizations.addRelationship($0) }
  56.  
  57. organizations.output()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement