Files
hello-algo/en/codes/go/chapter_hashing/array_hash_map.go
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

98 lines
1.8 KiB
Go

// File: array_hash_map.go
// Created Time: 2022-12-14
// Author: msk397 (machangxinq@gmail.com)
package chapter_hashing
import "fmt"
/* Key-value pair */
type pair struct {
key int
val string
}
/* Hash table implemented with an array */
type arrayHashMap struct {
buckets []*pair
}
/* Initialize the hash table */
func newArrayHashMap() *arrayHashMap {
// Initialize an array containing 100 buckets
buckets := make([]*pair, 100)
return &arrayHashMap{buckets: buckets}
}
/* Hash function */
func (a *arrayHashMap) hashFunc(key int) int {
index := key % 100
return index
}
/* Lookup operation */
func (a *arrayHashMap) get(key int) string {
index := a.hashFunc(key)
pair := a.buckets[index]
if pair == nil {
return "Not Found"
}
return pair.val
}
/* Insert operation */
func (a *arrayHashMap) put(key int, val string) {
pair := &pair{key: key, val: val}
index := a.hashFunc(key)
a.buckets[index] = pair
}
/* Remove operation */
func (a *arrayHashMap) remove(key int) {
index := a.hashFunc(key)
// Set to nil to mark the entry as removed
a.buckets[index] = nil
}
/* Get all key-value pairs */
func (a *arrayHashMap) pairSet() []*pair {
var pairs []*pair
for _, pair := range a.buckets {
if pair != nil {
pairs = append(pairs, pair)
}
}
return pairs
}
/* Get all keys */
func (a *arrayHashMap) keySet() []int {
var keys []int
for _, pair := range a.buckets {
if pair != nil {
keys = append(keys, pair.key)
}
}
return keys
}
/* Get all values */
func (a *arrayHashMap) valueSet() []string {
var values []string
for _, pair := range a.buckets {
if pair != nil {
values = append(values, pair.val)
}
}
return values
}
/* Print the hash table */
func (a *arrayHashMap) print() {
for _, pair := range a.buckets {
if pair != nil {
fmt.Println(pair.key, "->", pair.val)
}
}
}