hello-algo/codes/kotlin/chapter_hashing/simple_hash.kt
curtishd eadf4c86d4
Add kotlin code for the chapter of hashing (#1104)
* feat(kotlin): add kotlin code for dynamic programming.

* Update knapsack.kt

* feat(kotlin): add kotlin codes for graph.

* style(kotlin): reformatted the codes.

* feat(kotlin): add kotlin codes for the chapter of greedy.

* Update max_product_cutting.kt

* feat(kotlin): add kotlin code for chapter of hashing.

* style(kotlin): modified some comment

* Update array_hash_map.kt

* Update hash_map_chaining.kt

* Update hash_map_chaining.kt
2024-03-12 14:08:15 +08:00

62 lines
No EOL
1.2 KiB
Kotlin

/**
* File: simple_hash.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_hashing
const val MODULUS = 10_0000_0007
/* 加法哈希 */
fun addHash(key: String): Int {
var hash = 0L
for (c in key.toCharArray()) {
hash = (hash + c.code) % MODULUS
}
return hash.toInt()
}
/* 乘法哈希 */
fun mulHash(key: String): Int {
var hash = 0L
for (c in key.toCharArray()) {
hash = (31 * hash + c.code) % MODULUS
}
return hash.toInt()
}
/* 异或哈希 */
fun xorHash(key: String): Int {
var hash = 0
for (c in key.toCharArray()) {
hash = hash xor c.code
}
return hash and MODULUS
}
/* 旋转哈希 */
fun rotHash(key: String): Int {
var hash = 0L
for (c in key.toCharArray()) {
hash = ((hash shl 4) xor (hash shr 28) xor c.code.toLong()) % MODULUS
}
return hash.toInt()
}
/* Driver Code */
fun main() {
val key = "Hello 算法"
var hash: Int = addHash(key)
println("加法哈希值为 $hash")
hash = mulHash(key)
println("乘法哈希值为 $hash")
hash = xorHash(key)
println("异或哈希值为 $hash")
hash = rotHash(key)
println("旋转哈希值为 $hash")
}