feat: complete Dart codes for chapter_hashing (#566)

pull/568/head
liuyuxin 1 year ago committed by GitHub
parent ff58d4113c
commit 62e8f0df50
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,34 @@
/**
* File: built_in_hash.dart
* Created Time: 2023-06-25
* Author: liuyuxin (gvenusleo@gmail.com)
*/
import '../chapter_stack_and_queue/linkedlist_deque.dart';
/* Driver Code */
void main() {
int num = 3;
int hashNum = num.hashCode;
print("整数 $num 的哈希值为 $hashNum");
bool bol = true;
int hashBol = bol.hashCode;
print("布尔值 $bol 的哈希值为 $hashBol");
double dec = 3.14159;
int hashDec = dec.hashCode;
print("小数 $dec 的哈希值为 $hashDec");
String str = "Hello 算法";
int hashStr = str.hashCode;
print("字符串 $str 的哈希值为 $hashStr");
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
print("数组 $arr 的哈希值为 $hashArr");
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode;
print("节点对象 $obj 的哈希值为 $hashObj");
}

@ -0,0 +1,138 @@
/**
* File: hash_map_chaining.dart
* Created Time: 2023-06-24
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 键值对 */
class Pair {
int key;
String val;
Pair(this.key, this.val);
}
/* 链式地址哈希表 */
class HashMapChaining {
late int size; //
late int capacity; //
late double loadThres; //
late int extendRatio; //
late List<List<Pair>> buckets; //
/* 构造方法 */
HashMapChaining() {
size = 0;
capacity = 4;
loadThres = 2 / 3.0;
extendRatio = 2;
buckets = List.generate(capacity, (_) => []);
}
/* 哈希函数 */
int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
double loadFactor() {
return size / capacity;
}
/* 查询操作 */
String? get(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
// key val
for (Pair pair in bucket) {
if (pair.key == key) {
return pair.val;
}
}
// key null
return null;
}
/* 添加操作 */
void put(int key, String val) {
//
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
// key val
for (Pair pair in bucket) {
if (pair.key == key) {
pair.val = val;
return;
}
}
// key
Pair pair = Pair(key, val);
bucket.add(pair);
size++;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
//
bucket.removeWhere((Pair pair) => pair.key == key);
size--;
}
/* 扩容哈希表 */
void extend() {
//
List<List<Pair>> bucketsTmp = buckets;
//
capacity *= extendRatio;
buckets = List.generate(capacity, (_) => []);
size = 0;
//
for (List<Pair> bucket in bucketsTmp) {
for (Pair pair in bucket) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
void printHashMap() {
for (List<Pair> bucket in buckets) {
List<String> res = [];
for (Pair pair in bucket) {
res.add("${pair.key} -> ${pair.val}");
}
print(res);
}
}
}
/* Driver Code */
void main() {
/* 初始化哈希表 */
HashMapChaining map = HashMapChaining();
/* 添加操作 */
// (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
print("\n添加完成后,哈希表为\nKey -> Value");
map.printHashMap();
/* 查询操作 */
// key value
String? name = map.get(13276);
print("\n输入学号 13276 ,查询到姓名 ${name}");
/* 删除操作 */
// (key, value)
map.remove(12836);
print("\n删除 12836 后,哈希表为\nKey -> Value");
map.printHashMap();
}

@ -0,0 +1,157 @@
/**
* File: hash_map_open_addressing.dart
* Created Time: 2023-06-25
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 键值对 */
class Pair {
int key;
String val;
Pair(this.key, this.val);
}
/* 开放寻址哈希表 */
class HashMapOpenAddressing {
late int _size; //
late int _capacity; //
late double _loadThres; //
late int _extendRatio; //
late List<Pair?> _buckets; //
late Pair _removed; //
/* 构造方法 */
HashMapOpenAddressing() {
_size = 0;
_capacity = 4;
_loadThres = 2.0 / 3.0;
_extendRatio = 2;
_buckets = List.generate(_capacity, (index) => null);
_removed = Pair(-1, "-1");
}
/* 哈希函数 */
int hashFunc(int key) {
return key % _capacity;
}
/* 负载因子 */
double loadFactor() {
return _size / _capacity;
}
/* 查询操作 */
String? get(int key) {
int index = hashFunc(key);
// 线 index
for (int i = 0; i < _capacity; i++) {
//
int j = (index + i) % _capacity;
// key null
if (_buckets[j] == null) return null;
// key val
if (_buckets[j]!.key == key && _buckets[j] != _removed)
return _buckets[j]!.val;
}
return null;
}
/* 添加操作 */
void put(int key, String val) {
//
if (loadFactor() > _loadThres) {
extend();
}
int index = hashFunc(key);
// 线 index
for (int i = 0; i < _capacity; i++) {
//
int j = (index + i) % _capacity;
//
if (_buckets[j] == null || _buckets[j] == _removed) {
_buckets[j] = new Pair(key, val);
_size += 1;
return;
}
// key val
if (_buckets[j]!.key == key) {
_buckets[j]!.val = val;
return;
}
}
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
// 线 index
for (int i = 0; i < _capacity; i++) {
//
int j = (index + i) % _capacity;
// key
if (_buckets[j] == null) {
return;
}
// key
if (_buckets[j]!.key == key) {
_buckets[j] = _removed;
_size -= 1;
return;
}
}
}
/* 扩容哈希表 */
void extend() {
//
List<Pair?> bucketsTmp = _buckets;
//
_capacity *= _extendRatio;
_buckets = List.generate(_capacity, (index) => null);
_size = 0;
//
for (Pair? pair in bucketsTmp) {
if (pair != null && pair != _removed) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
void printHashMap() {
for (Pair? pair in _buckets) {
if (pair != null) {
print("${pair.key} -> ${pair.val}");
} else {
print(null);
}
}
}
}
/* Driver Code */
void main() {
/* 初始化哈希表 */
HashMapOpenAddressing map = HashMapOpenAddressing();
/* 添加操作 */
// (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
print("\n添加完成后,哈希表为\nKey -> Value");
map.printHashMap();
/* 查询操作 */
// key value
String? name = map.get(13276);
print("\n输入学号 13276 ,查询到姓名 $name");
/* 删除操作 */
// (key, value)
map.remove(16750);
print("\n删除 16750 后,哈希表为\nKey -> Value");
map.printHashMap();
}

@ -0,0 +1,62 @@
/**
* File: simple_hash.dart
* Created Time: 2023-06-25
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 加法哈希 */
int addHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (int i = 0; i < key.length; i++) {
hash = (hash + key.codeUnitAt(i)) % MODULUS;
}
return hash;
}
/* 乘法哈希 */
int mulHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (int i = 0; i < key.length; i++) {
hash = (31 * hash + key.codeUnitAt(i)) % MODULUS;
}
return hash;
}
/* 异或哈希 */
int xorHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (int i = 0; i < key.length; i++) {
hash ^= key.codeUnitAt(i);
}
return hash & MODULUS;
}
/* 旋转哈希 */
int rotHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (int i = 0; i < key.length; i++) {
hash = ((hash << 4) ^ (hash >> 28) ^ key.codeUnitAt(i)) % MODULUS;
}
return hash;
}
/* Dirver Code */
void main() {
String key = "Hello 算法";
int hash = addHash(key);
print("加法哈希值为 $hash");
hash = mulHash(key);
print("乘法哈希值为 $hash");
hash = xorHash(key);
print("异或哈希值为 $hash");
hash = rotHash(key);
print("旋转哈希值为 $hash");
}

@ -1,5 +1,5 @@
/** /**
* File: hash_map_chaining.java * File: hash_map_open_addressing.java
* Created Time: 2023-06-13 * Created Time: 2023-06-13
* Author: Krahets (krahets@163.com) * Author: Krahets (krahets@163.com)
*/ */

@ -32,7 +32,6 @@ public class simple_hash {
int hash = 0; int hash = 0;
final int MODULUS = 1000000007; final int MODULUS = 1000000007;
for (char c : key.toCharArray()) { for (char c : key.toCharArray()) {
System.out.println((int)c);
hash ^= (int) c; hash ^= (int) c;
} }
return hash & MODULUS; return hash & MODULUS;

@ -356,7 +356,29 @@ $$
=== "Dart" === "Dart"
```dart title="built_in_hash.dart" ```dart title="built_in_hash.dart"
int num = 3;
int hashNum = num.hashCode;
// 整数 3 的哈希值为 34803
bool bol = true;
int hashBol = bol.hashCode;
// 布尔值 true 的哈希值为 1231
double dec = 3.14159;
int hashDec = dec.hashCode;
// 小数 3.14159 的哈希值为 2570631074981783
String str = "Hello 算法";
int hashStr = str.hashCode;
// 字符串 Hello 算法 的哈希值为 468167534
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
// 数组 [12836, 小哈] 的哈希值为 976512528
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode;
// 节点对象 Instance of 'ListNode' 的哈希值为 1033450432
``` ```
在大多数编程语言中,**只有不可变对象才可作为哈希表的 `key`** 。假如我们将列表(动态数组)作为 `key` ,当列表的内容发生变化时,它的哈希值也随之改变,我们就无法在哈希表中查询到原先的 `value` 了。 在大多数编程语言中,**只有不可变对象才可作为哈希表的 `key`** 。假如我们将列表(动态数组)作为 `key` ,当列表的内容发生变化时,它的哈希值也随之改变,我们就无法在哈希表中查询到原先的 `value` 了。

Loading…
Cancel
Save