Last active
September 16, 2016 02:20
-
-
Save xanarin/34540660e7faf26b0e4b4803804fb699 to your computer and use it in GitHub Desktop.
An extension on the Equivalent Binary Trees - (https://tour.golang.org/concurrency/8) exercise from the Tour of Go Example on Goroutines - (https://tour.golang.org/concurrency/1).
This file contains 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
package main | |
import "golang.org/x/tour/tree" | |
import "fmt" | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
// Recursive Approach | |
if (t.Left != nil) { | |
Walk(t.Left, ch) | |
} | |
if (t.Right != nil) { | |
Walk(t.Right, ch) | |
} | |
ch <- t.Value | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(treeSize int, trees... *tree.Tree) bool { | |
var walkers = make([]chan int, len(trees)) | |
var treeValues = make([][]int, len(trees)) | |
// Create all channels and storage | |
for i, _ := range trees { | |
walkers[i] = make(chan int, treeSize) | |
treeValues[i] = make([]int, treeSize) | |
} | |
// Start all walkers | |
for i, tree := range trees { | |
go Walk(tree, walkers[i]) | |
} | |
for i := 0; i < treeSize; i++ { | |
for j, _ := range trees { | |
treeValues[j][i] = <- walkers[j] | |
} | |
} | |
for i := 0; i < treeSize; i++ { | |
// Iterate through all treeValues | |
for j := 1; j < len(treeValues); j++ { | |
foundMatch := false | |
for k := 0; k < treeSize; k++ { | |
if (treeValues[0][i] == treeValues[j][k]){ | |
foundMatch = true | |
break | |
} | |
} | |
// If a value from treeValues[0] isn't found in another | |
// treeValues[], then they are not all the Same and fail | |
if (foundMatch != true) { | |
return false | |
} | |
} | |
} | |
return true | |
} | |
func main() { | |
// Initalize array of trees | |
trees := make([] *tree.Tree, 1000000) | |
// Initialize trees | |
for i := 0; i < len(trees); i++ { | |
trees[i] = tree.New(1) | |
} | |
// Print result of Same on all of the trees | |
fmt.Println(Same(10, trees...)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment