Skip to content

Commit

Permalink
ImmutableStringRollingHash実装
Browse files Browse the repository at this point in the history
  • Loading branch information
mban259 committed May 13, 2024
1 parent e4ecdf4 commit bc7c198
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/main/kotlin/string/ImmutableStringRollingHash.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package string

class ImmutableStringRollingHash(private val radix: Long) {
import kotlin.random.Random

class ImmutableStringRollingHash {
companion object {
private const val MOD = (1L shl 61) - 1
private const val MASK31 = (1L shl 31) - 1
private const val MASK30 = (1L shl 30) - 1

// 文字列最大長、適宜変更すること
private const val MAX_LENGTH = 5000000

private fun multiply(l: Long, r: Long): Long {
val au = l shr 31
val ad = l and MASK31
Expand All @@ -24,4 +29,24 @@ class ImmutableStringRollingHash(private val radix: Long) {
return ((num % MOD) + MOD) % MOD
}
}

private val radix = Random.nextLong(MOD)
private val p = LongArray(MAX_LENGTH + 1) { 1 }

init {
for (i in 0 until MAX_LENGTH) {
p[i + 1] = multiply(p[i], radix)
}
}

fun createGetHash(s: String) = createGetHash(s.toCharArray())

fun createGetHash(array: CharArray): (Int, Int) -> Pair<Long, Int> {
val len = array.size
val table = LongArray(len + 1) { 0 }
for (i in array.indices) {
table[i + 1] = safeMod(multiply(radix, table[i]) + array[i].code)
}
return { begin, end -> safeMod(table[end] - multiply(p[end - begin], table[begin])) to end - begin }
}
}

0 comments on commit bc7c198

Please sign in to comment.