Fast Hash Algorithm Using Bit Offset To Avoid Collisions

Given a structure Personthat has string properties nameand surname, I would like to write a hashing algorithm that is efficient and avoids conflicts for people with removable names and surnames (e.g. Lara Ray and Ray Lara.).

I already know to distract from string concatenation in Swift, so ideally I think about XORusing two variables and shifting bits one of them to solve a plug-in problem. Is there something wrong with this?

struct Person {
    let name: String
    let surname: String

    var hashValue: Int {
        return surname.hashValue << 1 ^ name.hashValue
    }
}
+4
source share
1 answer
R Swift Boost hash_combine .

:

func hash_combine(seed: inout UInt, value: UInt) {
    let tmp = value &+ 0x9e3779b9 &+ (seed << 6) &+ (seed >> 2)
    seed ^= tmp
}

struct Person {
    let name: String
    let surname: String

    var hashValue: Int {
        var seed = UInt(0)
        hash_combine(seed: &seed, value: UInt(bitPattern: name.hashValue))
        hash_combine(seed: &seed, value: UInt(bitPattern: surname.hashValue))
        return Int(bitPattern: seed)
    }
}

Person(name: "Joe", surname: "Smith").hashValue // -5143836311621647467
Person(name: "Smith", surname: "Joe").hashValue // -5146825509308597586

, (. CGPoint).

" " : boost:: hash_combine

, , , , 1.

+1

Source: https://habr.com/ru/post/1683289/


All Articles