Merge pull request #110 from msk397/master

Add C++, Python, Go code for chapter_hashing
pull/126/head
Yudong Jin 2 years ago committed by GitHub
commit 221ed3f7ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,144 @@
/*
* File: array_hash_map.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "../include/include.hpp"
/* 键值对 int->String */
struct Entry {
public:
int key;
string val;
Entry(int key, string val) {
this->key = key;
this->val = val;
}
};
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private:
vector<Entry*> bucket;
public:
ArrayHashMap() {
// 初始化一个长度为 100 的桶(数组)
bucket= vector<Entry*>(100);
}
/* 哈希函数 */
int hashFunc(int key) {
int index = key % 100;
return index;
}
/* 查询操作 */
string get(int key) {
int index = hashFunc(key);
Entry* pair = bucket[index];
if (pair == nullptr) {
return "Not Found";
}
return pair->val;
}
/* 添加操作 */
void put(int key, string val) {
Entry* pair = new Entry(key, val);
int index = hashFunc(key);
bucket[index] = pair;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
// 置为 nullptr ,代表删除
bucket[index] = nullptr;
}
/* 获取所有键值对 */
vector<Entry*> entrySet() {
vector<Entry*> entrySet;
for (Entry* pair: bucket) {
if (pair != nullptr) {
entrySet.push_back(pair);
}
}
return entrySet;
}
/* 获取所有键 */
vector<int> keySet() {
vector<int> keySet;
for (Entry* pair: bucket) {
if (pair != nullptr) {
keySet.push_back(pair->key);
}
}
return keySet;
}
/* 获取所有值 */
vector<string> valueSet() {
vector<string> valueSet;
for (Entry* pair: bucket) {
if (pair != nullptr){
valueSet.push_back(pair->val);
}
}
return valueSet;
}
/* 打印哈希表 */
void print() {
for (Entry* kv: entrySet()) {
cout << kv->key << " -> " << kv->val << endl;
}
}
};
/* Driver Code */
int main() {
/* 初始化哈希表 */
ArrayHashMap map = ArrayHashMap();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
cout << "\n添加完成后,哈希表为\nKey -> Value" << endl;
map.print();
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
string name = map.get(15937);
cout << "\n输入学号 15937 ,查询到姓名 " << name << endl;
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.remove(10583);
cout << "\n删除 10583 后,哈希表为\nKey -> Value" << endl;
map.print();
/* 遍历哈希表 */
cout << "\n遍历键值对 Key->Value" << endl;
for (auto kv: map.entrySet()) {
cout << kv->key << " -> " << kv->val << endl;
}
cout << "\n单独遍历键 Key" << endl;
for (auto key: map.keySet()) {
cout << key << endl;
}
cout << "\n单独遍历值 Value" << endl;
for (auto val: map.valueSet()) {
cout << val << endl;
}
return 0;
}

@ -0,0 +1,53 @@
/*
* File: hash_map.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "../include/include.hpp"
/* Driver Code */
int main() {
/* 初始化哈希表 */
unordered_map<int, string> map;
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map[12836] = "小哈";
map[15937] = "小啰";
map[16750] = "小算";
map[13276] = "小法";
map[10583] = "小鸭";
cout << "\n添加完成后,哈希表为\nKey -> Value" << endl;
PrintUtil::printHashMap(map);
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
string name = map[15937];
cout << "\n输入学号 15937 ,查询到姓名 " << name << endl;
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.erase(10583);
cout << "\n删除 10583 后,哈希表为\nKey -> Value" << endl;
PrintUtil::printHashMap(map);
/* 遍历哈希表 */
cout << "\n遍历键值对 Key->Value" << endl;
for (auto kv: map) {
cout << kv.first << " -> " << kv.second << endl;
}
cout << "\n单独遍历键 Key" << endl;
for (auto key: map) {
cout << key.first << endl;
}
cout << "\n单独遍历值 Value" << endl;
for (auto val: map) {
cout << val.second << endl;
}
return 0;
}

@ -1,7 +1,7 @@
/* /*
* File: PrintUtil.hpp * File: PrintUtil.hpp
* Created Time: 2021-12-19 * Created Time: 2021-12-19
* Author: Krahets (krahets@163.com) * Author: Krahets (krahets@163.com), msk397 (machangxinq@gmail.com)
*/ */
#pragma once #pragma once
@ -277,4 +277,19 @@ class PrintUtil {
} }
cout << "[" + s.str() + "]" << '\n'; cout << "[" + s.str() + "]" << '\n';
} }
/**
* @brief Print a HashMap
*
* @tparam TKey
* @tparam TValue
* @param map
*/
// 定义模板参数 TKey 和 TValue用于指定键值对的类型
template <typename TKey, typename TValue>
static void printHashMap(unordered_map<TKey,TValue> map) {
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << '\n';
}
}
}; };

@ -0,0 +1,96 @@
// File: array_hash_map.go
// Created Time: 2022-12-14
// Author: msk397 (machangxinq@gmail.com)
package chapter_hashing
import "fmt"
/* 键值对 int->String */
type Entry struct {
key int
val string
}
/* 基于数组简易实现的哈希表 */
type ArrayHashMap struct {
bucket []*Entry
}
func newArrayHashMap() *ArrayHashMap {
// 初始化一个长度为 100 的桶(数组)
bucket := make([]*Entry, 100)
return &ArrayHashMap{bucket: bucket}
}
/* 哈希函数 */
func (a *ArrayHashMap) hashFunc(key int) int {
index := key % 100
return index
}
/* 查询操作 */
func (a *ArrayHashMap) get(key int) string {
index := a.hashFunc(key)
pair := a.bucket[index]
if pair == nil {
return "Not Found"
}
return pair.val
}
/* 添加操作 */
func (a *ArrayHashMap) put(key int, val string) {
pair := &Entry{key: key, val: val}
index := a.hashFunc(key)
a.bucket[index] = pair
}
/* 删除操作 */
func (a *ArrayHashMap) remove(key int) {
index := a.hashFunc(key)
// 置为 nil ,代表删除
a.bucket[index] = nil
}
/* 获取所有键对 */
func (a *ArrayHashMap) entrySet() []*Entry {
var pairs []*Entry
for _, pair := range a.bucket {
if pair != nil {
pairs = append(pairs, pair)
}
}
return pairs
}
/* 获取所有键 */
func (a *ArrayHashMap) keySet() []int {
var keys []int
for _, pair := range a.bucket {
if pair != nil {
keys = append(keys, pair.key)
}
}
return keys
}
/* 获取所有值 */
func (a *ArrayHashMap) valueSet() []string {
var values []string
for _, pair := range a.bucket {
if pair != nil {
values = append(values, pair.val)
}
}
return values
}
/* 打印哈希表 */
func (a *ArrayHashMap) print() {
for _, pair := range a.bucket {
if pair != nil {
fmt.Println(pair.key, "->", pair.val)
}
}
}

@ -0,0 +1,52 @@
// File: array_hash_map_test.go
// Created Time: 2022-12-14
// Author: msk397 (machangxinq@gmail.com)
package chapter_hashing
import (
"fmt"
"testing"
)
func TestArrayHashMap(t *testing.T) {
/* 初始化哈希表 */
mapp := newArrayHashMap()
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
mapp.put(12836, "小哈")
mapp.put(15937, "小啰")
mapp.put(16750, "小算")
mapp.put(13276, "小法")
mapp.put(10583, "小鸭")
fmt.Println("\n添加完成后哈希表为\nKey -> Value")
mapp.print()
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
name := mapp.get(15937)
fmt.Println("\n输入学号 15937 ,查询到姓名 " + name)
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
mapp.remove(10583)
fmt.Println("\n删除 10583 后,哈希表为\nKey -> Value")
mapp.print()
/* 遍历哈希表 */
fmt.Println("\n遍历键值对 Key->Value")
for _, kv := range mapp.entrySet() {
fmt.Println(kv.key, " -> ", kv.val)
}
fmt.Println("\n单独遍历键 Key")
for _, key := range mapp.keySet() {
fmt.Println(key)
}
fmt.Println("\n单独遍历值 Value")
for _, val := range mapp.valueSet() {
fmt.Println(val)
}
}

@ -0,0 +1,55 @@
// File: hash_map_test.go
// Created Time: 2022-12-14
// Author: msk397 (machangxinq@gmail.com)
package chapter_hashing
import (
"fmt"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestHashmap(t *testing.T) {
/* 初始化哈希表 */
mapp := make(map[int]string)
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
mapp[12836] = "小哈"
mapp[15937] = "小啰"
mapp[16750] = "小算"
mapp[13276] = "小法"
mapp[10583] = "小鸭"
fmt.Println("\n添加完成后哈希表为\nKey -> Value")
PrintMap(mapp)
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
name := mapp[15937]
fmt.Println("\n输入学号 15937 ,查询到姓名 ", name)
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
delete(mapp, 10583)
fmt.Println("\n删除 10583 后,哈希表为\nKey -> Value")
PrintMap(mapp)
/* 遍历哈希表 */
// 遍历键值对 key->value
fmt.Println("\n遍历键值对 Key->Value")
for key, value := range mapp {
fmt.Println(key, "->", value)
}
// 单独遍历键 key
fmt.Println("\n单独遍历键 Key")
for key := range mapp {
fmt.Println(key)
}
// 单独遍历值 value
fmt.Println("\n单独遍历值 Value")
for _, value := range mapp {
fmt.Println(value)
}
}

@ -1,6 +1,6 @@
// File: print_utils.go // File: print_utils.go
// Created Time: 2022-12-03 // Created Time: 2022-12-03
// Author: Reanon (793584285@qq.com), Krahets (krahets@163.com) // Author: Reanon (793584285@qq.com), Krahets (krahets@163.com), msk397 (machangxinq@gmail.com)
package pkg package pkg
@ -96,3 +96,10 @@ func showTrunk(t *trunk) {
showTrunk(t.prev) showTrunk(t.prev)
fmt.Print(t.str) fmt.Print(t.str)
} }
// PrintMap Print a hash map
func PrintMap[K comparable, V any](m map[K]V) {
for key, value := range m {
fmt.Println(key, "->", value)
}
}

@ -21,7 +21,7 @@ class Entry {
class ArrayHashMap { class ArrayHashMap {
private List<Entry> bucket; private List<Entry> bucket;
public ArrayHashMap() { public ArrayHashMap() {
// 初始化一个长度为 10 的桶(数组) // 初始化一个长度为 100 的桶(数组)
bucket = new ArrayList<>(); bucket = new ArrayList<>();
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
bucket.add(null); bucket.add(null);

@ -0,0 +1,113 @@
"""
File: array_hash_map.py
Created Time: 2022-12-14
Author: msk397 (machangxinq@gmail.com)
"""
""" 键值对 int->String """
class Entry:
def __init__(self, key, val):
self.key = key
self.val = val
""" 基于数组简易实现的哈希表 """
class ArrayHashMap:
def __init__(self):
# 初始化一个长度为 100 的桶(数组)
self.bucket = [None] * 100
""" 哈希函数 """
def hashFunc(self, key):
index = key % 100
return index
""" 查询操作 """
def get(self, key):
index = self.hashFunc(key)
pair = self.bucket[index]
if pair is None:
return None
return pair.val
""" 添加操作 """
def put(self, key, val):
pair = Entry(key, val)
index = self.hashFunc(key)
self.bucket[index] = pair
""" 删除操作 """
def remove(self, key):
index = self.hashFunc(key)
# 置为None代表删除
self.bucket[index] = None
""" 获取所有键值对 """
def entrySet(self):
result = []
for pair in self.bucket:
if pair is not None:
result.append(pair)
return result
""" 获取所有键 """
def keySet(self):
result = []
for pair in self.bucket:
if pair is not None:
result.append(pair.key)
return result
""" 获取所有值 """
def valueSet(self):
result = []
for pair in self.bucket:
if pair is not None:
result.append(pair.val)
return result
""" 打印哈希表 """
def print(self):
for pair in self.bucket:
if pair is not None:
print(pair.key, "->", pair.val)
""" Driver Code """
if __name__ == "__main__":
""" 初始化哈希表 """
mapp = ArrayHashMap()
""" 添加操作 """
# 在哈希表中添加键值对 (key, value)
mapp.put(12836, "小哈")
mapp.put(15937, "小啰")
mapp.put(16750, "小算")
mapp.put(13276, "小法")
mapp.put(10583, "小鸭")
print("\n添加完成后,哈希表为\nKey -> Value")
mapp.print()
""" 查询操作 """
# 向哈希表输入键 key ,得到值 value
name = mapp.get(15937)
print("\n输入学号 15937 ,查询到姓名 " + name)
""" 删除操作 """
# 在哈希表中删除键值对 (key, value)
mapp.remove(10583)
print("\n删除 10583 后,哈希表为\nKey -> Value")
mapp.print()
""" 遍历哈希表 """
print("\n遍历键值对 Key->Value")
for pair in mapp.entrySet():
print(pair.key, "->", pair.val)
print("\n单独遍历键 Key")
for key in mapp.keySet():
print(key)
print("\n单独遍历值 Value")
for val in mapp.valueSet():
print(val)

@ -0,0 +1,49 @@
"""
File: hash_map.py
Created Time: 2022-12-14
Author: msk397 (machangxinq@gmail.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
""" Driver Code """
if __name__ == "__main__":
""" 初始化哈希表 """
mapp = {}
""" 添加操作 """
# 在哈希表中添加键值对 (key, value)
mapp[12836] = "小哈"
mapp[15937] = "小啰"
mapp[16750] = "小算"
mapp[13276] = "小法"
mapp[10583] = "小鸭"
print("\n添加完成后,哈希表为\nKey -> Value")
print_dict(mapp)
""" 查询操作 """
# 向哈希表输入键 key ,得到值 value
name = mapp[15937]
print("\n输入学号 15937 ,查询到姓名 " + name)
""" 删除操作 """
# 在哈希表中删除键值对 (key, value)
mapp.pop(10583)
print("\n删除 10583 后,哈希表为\nKey -> Value")
print_dict(mapp)
""" 遍历哈希表 """
print("\n遍历键值对 Key->Value")
for key, value in mapp.items():
print(key, "->", value)
print("\n单独遍历键 Key")
for key in mapp.keys():
print(key)
print("\n单独遍历值 Value")
for val in mapp.values():
print(val)

@ -7,4 +7,4 @@ import collections
from typing import List from typing import List
from .linked_list import ListNode, list_to_linked_list, linked_list_to_list, get_list_node from .linked_list import ListNode, list_to_linked_list, linked_list_to_list, get_list_node
from .binary_tree import TreeNode, list_to_tree, tree_to_list, get_tree_node from .binary_tree import TreeNode, list_to_tree, tree_to_list, get_tree_node
from .print_util import print_matrix, print_linked_list, print_tree from .print_util import print_matrix, print_linked_list, print_tree, print_dict

@ -1,7 +1,7 @@
''' '''
File: print_util.py File: print_util.py
Created Time: 2021-12-11 Created Time: 2021-12-11
Author: Krahets (krahets@163.com) Author: Krahets (krahets@163.com), msk397 (machangxinq@gmail.com)
''' '''
import copy import copy
@ -72,3 +72,12 @@ def print_tree(root, prev=None, isLeft=False):
prev.str = prev_str prev.str = prev_str
trunk.str = ' |' trunk.str = ' |'
print_tree(root.left, trunk, False) print_tree(root.left, trunk, False)
def print_dict(d):
"""Print a dict
Args:
d ([type]): [description]
"""
for key, value in d.items():
print(key, '->', value)

@ -63,19 +63,70 @@ comments: true
=== "C++" === "C++"
```cpp title="hash_map.cpp" ```cpp title="hash_map.cpp"
/* 初始化哈希表 */
unordered_map<int, string> map;
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map[12836] = "小哈";
map[15937] = "小啰";
map[16750] = "小算";
map[13276] = "小法";
map[10583] = "小鸭";
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
string name = map[15937];
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.erase(10583);
``` ```
=== "Python" === "Python"
```python title="hash_map.py" ```python title="hash_map.py"
""" 初始化哈希表 """
mapp = {}
""" 添加操作 """
# 在哈希表中添加键值对 (key, value)
mapp[12836] = "小哈"
mapp[15937] = "小啰"
mapp[16750] = "小算"
mapp[13276] = "小法"
mapp[10583] = "小鸭"
""" 查询操作 """
# 向哈希表输入键 key ,得到值 value
name = mapp[15937]
""" 删除操作 """
# 在哈希表中删除键值对 (key, value)
mapp.pop(10583)
``` ```
=== "Go" === "Go"
```go title="hash_map.go" ```go title="hash_map_test.go"
/* 初始化哈希表 */
mapp := make(map[int]string)
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
mapp[12836] = "小哈"
mapp[15937] = "小啰"
mapp[16750] = "小算"
mapp[13276] = "小法"
mapp[10583] = "小鸭"
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
name := mapp[15937]
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
delete(mapp, 10583)
``` ```
=== "JavaScript" === "JavaScript"
@ -125,19 +176,52 @@ comments: true
=== "C++" === "C++"
```cpp title="hash_map.cpp" ```cpp title="hash_map.cpp"
/* 遍历哈希表 */
// 遍历键值对 key->value
for (auto kv: map) {
cout << kv.first << " -> " << kv.second << endl;
}
// 单独遍历键 key
for (auto key: map) {
cout << key.first << endl;
}
// 单独遍历值 value
for (auto val: map) {
cout << val.second << endl;
}
``` ```
=== "Python" === "Python"
```python title="hash_map.py" ```python title="hash_map.py"
""" 遍历哈希表 """
# 遍历键值对 key->value
for key, value in mapp.items():
print(key, "->", value)
# 单独遍历键 key
for key in mapp.keys():
print(key)
# 单独遍历值 value
for value in mapp.values():
print(value)
``` ```
=== "Go" === "Go"
```go title="hash_map.go" ```go title="hash_map_test.go"
/* 遍历哈希表 */
// 遍历键值对 key->value
for key, value := range mapp {
fmt.Println(key, "->", value)
}
// 单独遍历键 key
for key := range mapp {
fmt.Println(key)
}
// 单独遍历值 value
for _, value := range mapp {
fmt.Println(value)
}
``` ```
=== "JavaScript" === "JavaScript"
@ -242,19 +326,146 @@ $$
=== "C++" === "C++"
```cpp title="array_hash_map.cpp" ```cpp title="array_hash_map.cpp"
/* 键值对 int->String */
struct Entry {
public:
int key;
string val;
Entry(int key, string val) {
this->key = key;
this->val = val;
}
};
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private:
vector<Entry*> bucket;
public:
ArrayHashMap() {
// 初始化一个长度为 100 的桶(数组)
bucket= vector<Entry*>(100);
}
/* 哈希函数 */
int hashFunc(int key) {
int index = key % 100;
return index;
}
/* 查询操作 */
string get(int key) {
int index = hashFunc(key);
Entry* pair = bucket[index];
return pair->val;
}
/* 添加操作 */
void put(int key, string val) {
Entry* pair = new Entry(key, val);
int index = hashFunc(key);
bucket[index] = pair;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
// 置为空字符,代表删除
bucket[index] = nullptr;
}
};
``` ```
=== "Python" === "Python"
```python title="array_hash_map.py" ```python title="array_hash_map.py"
""" 键值对 int->String """
class Entry:
def __init__(self, key, val):
self.key = key
self.val = val
""" 基于数组简易实现的哈希表 """
class ArrayHashMap:
def __init__(self):
# 初始化一个长度为 100 的桶(数组)
self.bucket = [None] * 100
""" 哈希函数 """
def hashFunc(self, key):
index = key % 100
return index
""" 查询操作 """
def get(self, key):
index = self.hashFunc(key)
pair = self.bucket[index]
if pair is None:
return None
return pair.val
""" 添加操作 """
def put(self, key, val):
pair = Entry(key, val)
index = self.hashFunc(key)
self.bucket[index] = pair
""" 删除操作 """
def remove(self, key):
index = self.hashFunc(key)
# 置为空字符,代表删除
self.bucket[index] = None
``` ```
=== "Go" === "Go"
```go title="array_hash_map.go" ```go title="array_hash_map.go"
/* 键值对 int->String */
type Entry struct {
key int
val string
}
/* 基于数组简易实现的哈希表 */
type ArrayHashMap struct {
bucket []*Entry
}
func newArrayHashMap() *ArrayHashMap {
// 初始化一个长度为 100 的桶(数组)
bucket := make([]*Entry, 100)
return &ArrayHashMap{bucket: bucket}
}
/* 哈希函数 */
func (a *ArrayHashMap) hashFunc(key int) int {
index := key % 100
return index
}
/* 查询操作 */
func (a *ArrayHashMap) get(key int) string {
index := a.hashFunc(key)
pair := a.bucket[index]
if pair == nil {
return "Not Found"
}
return pair.val
}
/* 添加操作 */
func (a *ArrayHashMap) put(key int, val string) {
pair := &Entry{key: key, val: val}
index := a.hashFunc(key)
a.bucket[index] = pair
}
/* 删除操作 */
func (a *ArrayHashMap) remove(key int) {
index := a.hashFunc(key)
// 置为空字符,代表删除
a.bucket[index] = nil
}
``` ```
=== "JavaScript" === "JavaScript"

Loading…
Cancel
Save