This commit is contained in:
krahets
2024-04-13 21:17:44 +08:00
parent 9332a91e26
commit 6afa70e7bc
55 changed files with 334 additions and 182 deletions

View File

@ -560,6 +560,7 @@ index = hash(key) % capacity
/* 加法雜湊 */
fun addHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = (hash + c.code) % MODULUS
}
@ -569,6 +570,7 @@ index = hash(key) % capacity
/* 乘法雜湊 */
fun mulHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = (31 * hash + c.code) % MODULUS
}
@ -578,6 +580,7 @@ index = hash(key) % capacity
/* 互斥或雜湊 */
fun xorHash(key: String): Int {
var hash = 0
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = hash xor c.code
}
@ -587,6 +590,7 @@ index = hash(key) % capacity
/* 旋轉雜湊 */
fun rotHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = ((hash shl 4) xor (hash shr 28) xor c.code.toLong()) % MODULUS
}

View File

@ -1312,7 +1312,7 @@ comments: true
```kotlin title="hash_map_chaining.kt"
/* 鏈式位址雜湊表 */
class HashMapChaining() {
class HashMapChaining {
var size: Int // 鍵值對數量
var capacity: Int // 雜湊表容量
val loadThres: Double // 觸發擴容的負載因子閾值

View File

@ -1464,7 +1464,7 @@ index = hash(key) % capacity
/* 建構子 */
ArrayHashMap *newArrayHashMap() {
ArrayHashMap *hmap = malloc(sizeof(ArrayHashMap));
for (int i = 0; i < MAX_SIZE; i++) {
for (int i=0; i < MAX_SIZE; i++) {
hmap->buckets[i] = NULL;
}
return hmap;
@ -1646,7 +1646,8 @@ index = hash(key) % capacity
fun valueSet(): MutableList<String> {
val valueSet = mutableListOf<String>()
for (pair in buckets) {
pair?.let { valueSet.add(it._val) }
if (pair != null)
valueSet.add(pair._val)
}
return valueSet
}
@ -1656,7 +1657,7 @@ index = hash(key) % capacity
for (kv in pairSet()) {
val key = kv.key
val _val = kv._val
println("${key} -> ${_val}")
println("$key -> $_val")
}
}
}