From 85d04412c50cdd9ae5f6ed497607e3ab9c5632f0 Mon Sep 17 00:00:00 2001 From: Fenris Lycaon Date: Sat, 1 Oct 2022 14:34:56 +0530 Subject: [PATCH] Added Trie in GOLang --- GO/Structure/trie/main.go | 75 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 GO/Structure/trie/main.go diff --git a/GO/Structure/trie/main.go b/GO/Structure/trie/main.go new file mode 100644 index 0000000..9c568fb --- /dev/null +++ b/GO/Structure/trie/main.go @@ -0,0 +1,75 @@ +package main + +import "fmt" + +// AlphabetSize is the number of possible characters in the trie +const AlphabetSize = 26 + +// Node represents each node in the trie +type Node struct { + children [26]*Node + isEnd bool +} + +// Trie represenst a trie and has a pointer to the root node +type Trie struct { + root *Node +} + +// InitTrie will create new Trie +func InitTrie() *Trie { + result := &Trie{root: &Node{}} + return result +} + +// Insert will take in a word and add it to the trie +func (t *Trie) Insert(w string) { + wordLength := len(w) + currentNode := t.root + for i := 0; i < wordLength; i++ { + charIndex := w[i] - 'a' + if currentNode.children[charIndex] == nil { + currentNode.children[charIndex] = &Node{} + } + currentNode = currentNode.children[charIndex] + } + currentNode.isEnd = true +} + +// Search will take in a word and RETURN true is that word is included in the trie +func (t *Trie) Search(w string) bool { + wordLength := len(w) + currentNode := t.root + for i := 0; i < wordLength; i++ { + charIndex := w[i] - 'a' + if currentNode.children[charIndex] == nil { + return false + } + currentNode = currentNode.children[charIndex] + } + if currentNode.isEnd == true { + return true + } + + return false +} + +func main() { + myTrie := InitTrie() + + toAdd := []string{ + "aragorn", + "aragon", + "argon", + "eragon", + "oregon", + "oregano", + "oreo", + } + + for _, v := range toAdd { + myTrie.Insert(v) + } + + fmt.Println(myTrie.Search("wizard")) +}