Skip to content

Instantly share code, notes, and snippets.

@charsyam
Created September 28, 2013 15:36
Show Gist options
  • Save charsyam/6743224 to your computer and use it in GitHub Desktop.
Save charsyam/6743224 to your computer and use it in GitHub Desktop.
Simple Universalhash
package main
import (
"fmt"
"math/rand"
"time"
)
type UniversalHash struct {
table [] byte
size int
}
func (o *UniversalHash) Init(size int) *UniversalHash {
return &UniversalHash{
table: make([]byte, size),
size: size,
}
}
func (o *UniversalHash) createTable() {
for i := 0; i < len(o.table); i++ {
o.table[i] = (byte)(rand.Int() % o.size)
}
}
func (o *UniversalHash) hash(key string) int {
byteArray := []byte(key)
hashValue := 0
for i := 0; i < len(byteArray); i++ {
hashValue += ((int)(byteArray[i]*o.table[i]))+1
}
return hashValue % o.size
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
hash := new(UniversalHash).Init(5)
hash.createTable()
v := hash.hash("aaaaa")
fmt.Println(v)
v = hash.hash("bbbbb")
fmt.Println(v)
v = hash.hash("ccccc")
fmt.Println(v)
v = hash.hash("ddddd")
fmt.Println(v)
v = hash.hash("eeeee")
fmt.Println(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment