Skip to content

Instantly share code, notes, and snippets.

@helloworldsmart
Last active May 19, 2018 10:01
Show Gist options
  • Select an option

  • Save helloworldsmart/4474cfb98db809da462d06aa8cf77930 to your computer and use it in GitHub Desktop.

Select an option

Save helloworldsmart/4474cfb98db809da462d06aa8cf77930 to your computer and use it in GitHub Desktop.
Binary tree
import Foundation
class ClassNode {
var value: Double?
var operation: String?
var leftChild: ClassNode?
var rightChild: ClassNode?
init(value: Double? = nil, operation: String? = nil, leftChild:ClassNode? = nil, rightChild: ClassNode? = nil) {
self.value = value
self.operation = operation
self.leftChild = leftChild
self.rightChild = rightChild
}
func evaluate() -> Double {
if let op = operation {
guard let leftChild = leftChild else { fatalError("no left child in binary operation") }
guard let rightChild = rightChild else { fatalError("no right child in binary operation") }
switch op {
case "+":
return leftChild.evaluate() + rightChild.evaluate()
case "-":
return leftChild.evaluate() - rightChild.evaluate()
case "*":
return leftChild.evaluate() * rightChild.evaluate()
case "/":
return leftChild.evaluate() / rightChild.evaluate()
case "^":
// var value = rightChild.evaluate()
// let sum = leftChild.evaluate()
// while (value > 1) {
// value -= 1
// sum * leftChild.evaluate()
// }
// return sum
return pow(leftChild.evaluate(), rightChild.evaluate())
default:
fatalError("Undefined operation")
}
} else {
guard let value = value else { fatalError("No value provided") }
return value
}
}
}
let formula = ClassNode(operation: "+", leftChild: ClassNode(operation: "*", leftChild: ClassNode(value: 2), rightChild: ClassNode(value: 3)), rightChild: ClassNode(value: 4))
print(formula.evaluate())
let BMIformula = ClassNode(operation: "/", leftChild: ClassNode(value: 88), rightChild: ClassNode(operation: "^", leftChild: ClassNode(value: 1.90), rightChild: ClassNode(value: 2)))
print(BMIformula.evaluate())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment