Last active
January 3, 2021 22:49
-
-
Save krzyzanowskim/52d4ae521124d7189caaace632327d94 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
class Node: Equatable, CustomStringConvertible { | |
let value: Int | |
var children: [Node] | |
init(value: Int, children: [Node]) { | |
self.value = value | |
self.children = children | |
} | |
var description: String { | |
return "\(value)\(!children.isEmpty ? children.description : String())" | |
} | |
static func == (lhs: Node, rhs: Node) -> Bool { | |
lhs.value == rhs.value | |
} | |
@discardableResult | |
func filter(for value: Int) -> Bool { | |
for child in children where !child.filter(for: value) { | |
children.removeAll(where: { $0 == child }) | |
} | |
return self.value == value || !children.isEmpty | |
} | |
@discardableResult | |
func filter(where predicate: (Node) -> Bool) -> Bool { | |
for child in children where !child.filter(where: predicate) { | |
children.removeAll(where: { $0 == child }) | |
} | |
return predicate(self) || !children.isEmpty | |
} | |
} | |
var tree = Node(value: 0, children: [ | |
Node(value: 1, children: [ | |
Node(value: 3, children: [ | |
Node(value: 4, children: [ | |
Node(value: 6, children: []), | |
]), | |
Node(value: 5, children: [ | |
Node(value: 6, children: []), | |
]), | |
]), | |
]), | |
Node(value: 2, children: [ | |
Node(value: 4, children: []), | |
]), | |
]) | |
//tree.filter(for: 6) | |
tree.filter(where: { $0.value == 6 }) | |
print(tree.children) // [1[3[4[6], 5[6]]]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment