Skip to content

Instantly share code, notes, and snippets.

@rachelcarmena
Created September 28, 2021 12:15
Show Gist options
  • Save rachelcarmena/5f5ef8a589c937cf58d061e90ca50cc1 to your computer and use it in GitHub Desktop.
Save rachelcarmena/5f5ef8a589c937cf58d061e90ca50cc1 to your computer and use it in GitHub Desktop.
evaluateExp
package kata
import (
"rachel/tree"
)
func EvaluateExp(s string) int {
count := 0
trees := tree.FullBinaryTreesFor(s)
for _, tree := range trees {
if evalBinaryTree(tree) {
count ++
}
}
return count
}
func evalBinaryTree(tree *tree.BinaryTree) bool {
if tree.Left == nil && tree.Right == nil {
return tree.Value == 'T'
}
switch tree.Value {
case '&':
return evalBinaryTree(tree.Left) && evalBinaryTree(tree.Right)
case '|':
return evalBinaryTree(tree.Left) || evalBinaryTree(tree.Right)
case '^':
return evalBinaryTree(tree.Left) != evalBinaryTree(tree.Right)
}
return false
}
package tree
type BinaryTree struct {
Value byte
Left *BinaryTree
Right *BinaryTree
}
func FullBinaryTreesFor(s string) []*BinaryTree {
length := len(s)
if length == 1 {
return []*BinaryTree{&BinaryTree{Value: s[0]}}
}
var result []*BinaryTree
for i := 0; i < (length-1)/2; i++ {
e := i*2+1 // Odd index
ltrees := FullBinaryTreesFor(s[:e])
rtrees := FullBinaryTreesFor(s[(e+1):])
for _, ltree := range ltrees {
for _, rtree := range rtrees {
result = append(result, &BinaryTree{s[e], ltree, rtree})
}
}
}
return result
}
@cassidoo
Copy link

Love that you used binary trees!!

@rachelcarmena
Copy link
Author

Love that you used binary trees!!

Thanks @cassidoo, you're the best!! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment