Last active
October 8, 2015 17:56
-
-
Save urielhdz/25a86726bce759444255 to your computer and use it in GitHub Desktop.
Hash Table using Go
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( | |
"fmt" | |
"math" | |
"bufio" | |
"os" | |
"strings" | |
) | |
type HashEntry struct{ | |
value int | |
key string | |
next *HashEntry | |
} | |
type HashTable struct{ | |
hash_entries []HashEntry | |
maximum int | |
} | |
func (self *HashTable) put(key string, value int) { | |
// TO DO: Replace if key is the same | |
position := hash(key,self.maximum) | |
new_hash_entry := HashEntry{key: key, value: value} | |
hash_entry := &self.hash_entries[position] | |
if hash_entry.isNil(){ | |
self.hash_entries[position] = new_hash_entry | |
}else { | |
for hash_entry.next != nil { | |
hash_entry = hash_entry.next | |
} | |
hash_entry.next = &new_hash_entry | |
} | |
} | |
func (self *HashTable) get(key string) int{ | |
position := hash(key,self.maximum) | |
hash_entry := self.hash_entries[position] | |
for !hash_entry.isNil(){ | |
if hash_entry.key == key{ | |
return hash_entry.value | |
} | |
if hash_entry.next == nil{ | |
break | |
} | |
hash_entry = *hash_entry.next | |
} | |
return 0 | |
} | |
func(self HashEntry) isNil() bool{ | |
return self.value == 0 && self.key == "" | |
} | |
func main() { | |
var option,value int | |
hash_table := HashTable{maximum: 20, hash_entries: make([]HashEntry, 20)} | |
Loop: | |
for true { | |
fmt.Println("Elige una opción: \n1.- Ingresar al HashTable \n2.- Leer del HashTable \n3.- Salir") | |
fmt.Scan(&option) | |
switch { | |
case option == 1: | |
text := getText("Clave a ingresar: ") | |
fmt.Println("Numero para la clave") | |
fmt.Scan(&value) | |
hash_table.put(text, value) | |
case option == 2: | |
text := getText("Clave a buscar: ") | |
fmt.Println(hash_table.get(text)) | |
case option == 3: | |
break Loop | |
} | |
} | |
} | |
func getText(description string) string{ | |
reader := bufio.NewReader(os.Stdin) | |
fmt.Println(description) | |
text, _ := reader.ReadString('\n') | |
text = strings.Replace(text,"\n","",-1) | |
return text | |
} | |
func hash(data string,maximum int) int{ | |
h := 0; | |
for _,c := range data{ | |
h = h + int(c) | |
} | |
h = int(math.Abs(float64(h))) // Convert to positive if negative | |
return h % maximum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment