Skip to content

Commit

Permalink
Merge 465e57f into 3b8fe7e
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Oct 10, 2018
2 parents 3b8fe7e + 465e57f commit 6643801
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ problems from
* [Day 46](https://github.com/vaskoz/dailycodingproblem-go/issues/103)
* [Day 47](https://github.com/vaskoz/dailycodingproblem-go/issues/105)
* [Day 49](https://github.com/vaskoz/dailycodingproblem-go/issues/107)
* [Day 50](https://github.com/vaskoz/dailycodingproblem-go/issues/110)
46 changes: 46 additions & 0 deletions day50/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package day50

// Operator represents the arithmetic operations.
type Operator int

const (
// NON is a zero value of this constant.
NON Operator = iota
// ADD is addition
ADD
// SUB is subtraction
SUB
// MUL is multiplication
MUL
// DIV is division
DIV
)

// ArithmeticTree represents either a node operator or a leaf value.
type ArithmeticTree struct {
val int
op Operator
left, right *ArithmeticTree
}

// Calculate takes an ArithmeticTree and returns its calculated value.
// Runs in O(N) in that it only views the tree nodes once.
func Calculate(tree *ArithmeticTree) int {
if tree.op == NON {
return tree.val
}
left := Calculate(tree.left)
right := Calculate(tree.right)
var result int
switch tree.op {
case ADD:
result = left + right
case SUB:
result = left - right
case MUL:
result = left * right
case DIV:
result = left / right
}
return result
}
34 changes: 34 additions & 0 deletions day50/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day50

import "testing"

var testcases = []struct {
tree *ArithmeticTree
expected int
}{
{&ArithmeticTree{op: MUL,
left: &ArithmeticTree{op: ADD, left: &ArithmeticTree{val: 3}, right: &ArithmeticTree{val: 2}},
right: &ArithmeticTree{op: ADD, left: &ArithmeticTree{val: 4}, right: &ArithmeticTree{val: 5}}},
45},
{&ArithmeticTree{op: SUB,
left: &ArithmeticTree{op: DIV, left: &ArithmeticTree{val: 100}, right: &ArithmeticTree{val: 2}},
right: &ArithmeticTree{op: DIV, left: &ArithmeticTree{val: 100}, right: &ArithmeticTree{val: 5}}},
30},
}

func TestCalculate(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := Calculate(tc.tree); result != tc.expected {
t.Errorf("Expected %d got %d", tc.expected, result)
}
}
}

func BenchmarkCalculate(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Calculate(tc.tree)
}
}
}

0 comments on commit 6643801

Please sign in to comment.