Created
August 15, 2019 02:56
-
-
Save luqmansen/b8337c23184ecc64624764990d4e099e to your computer and use it in GitHub Desktop.
Simple Go Hash Table
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 ( | |
"bufio" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
func main() { | |
//Get the moby dick novel | |
res, err := http.Get("http://www.gutenberg.org/files/2701/old/moby10b.txt") | |
if err != nil{ | |
log.Fatal(err) | |
} | |
//Scan the page | |
//NewScanner takes a reader and res.Body implements the reader interface | |
scanner := bufio.NewScanner(res.Body) | |
defer res.Body.Close() | |
//Set the split function for the scanning operation | |
scanner.Split(bufio.ScanWords) | |
//Create a slice of slice of string to hold slices of word | |
buckets := make([][]string, 12) | |
//Create slices to hold words | |
for i := 0; i<12; i++{ | |
buckets = append(buckets, []string{}) | |
} | |
//Loop over the word, put it into our slices for each bucket | |
for scanner.Scan(){ | |
word := scanner.Text() | |
n := HashBucket(word,12) | |
buckets[n] = append(buckets[n], word) | |
} | |
//Print len of each bucket | |
for i:= 0; i<12; i++{ | |
fmt.Println(i, " - ", len(buckets[i])) | |
} | |
//Try to print one of the bucket here | |
//fmt.Println(buckets[6]) | |
} | |
//This function just determine where the word is going to be stored in bucket | |
//returning a number of bucket where the word should be stored | |
func HashBucket(word string, buckets int) int { | |
var sum int | |
for _, v := range word{ | |
sum += int(v) | |
} | |
return sum % buckets | |
//Comment function above and uncomment function below | |
//for more uneven distribution | |
//return len(word) % buckets | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment