-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringEqualsHash.kt
45 lines (40 loc) · 1.06 KB
/
StringEqualsHash.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package other
/**
*
* comparing two strings with a hash
*
*/
class StringEqualsHash {
/**
*
* computes the hash of a string according to the formula:
*
* hash(abc) = a.code * primeCoefficient⁰ + b.code * primeCoefficient¹ + c.code * primeCoefficient²
*
* @return returns the hash of the string
*
*/
private fun String.hash() : Int {
var result = 0
var factor = 1
forEach { symbol ->
result += symbol.code * factor
factor *= primeCoefficient
}
return result.mod(Int.MAX_VALUE)
}
fun equals(source: String, pattern: String) : Boolean =
if (source.length != pattern.length) false else source.hash() == pattern.hash()
companion object {
/**
*
* I chose the nearest prime number for the size of the alphabet
*
* my alphabet is [a-z] [A-Z] ! , .
*
* size of the alphabet = 26 + 26 + 3 = 55 (is not prime)
*
*/
private const val primeCoefficient = 53
}
}