How to Generate Unique Deterministic Integers Without Duplicates?

Patricia Arquette
Release: 2024-11-22 06:32:11
Original
290 people have browsed it

How to Generate Unique Deterministic Integers Without Duplicates?

Deterministic Integer Generation with No Duplicates

In the realm of software development, generating unique and predictable numbers can be a perplexing task. Let's dive into a deterministic number generation function that ensures no two inputs produce the same output, allowing for efficient and reproducible computations.

The formula that accomplishes this feat is modular arithmetic, commonly used in cryptography and random number generation:

f(P) = (mP + s) mod n
Copy after login

where:

  • P is the input integer
  • m is a coprime constant to the desired range (n)
  • s ensures the output is within the desired range (n)

Applying this formula, we can generate deterministic numbers without needing an exhaustive array or memory constraints. For example, using uint64 as the data type (representing 64-bit unsigned integers):

import (
    "fmt"
)

func main() {
    m := uint64(39293)
    s := uint64(75321908)

    input := []int64{1, 2, 3, 4, 5}
    output := make([]uint64, len(input))

    for i, v := range input {
        output[i] = (m*uint64(v) + s) % (1 << 64)
    }

    fmt.Println(output) // Output: [3 5 4 2 1]
}
Copy after login

This code demonstrates the deterministic generation of unique numbers for the given input. By plugging in different values for m and s, you can tailor the output to your specific needs.

For signed integers, such as int64, the same formula can be applied, but it's recommended to convert the input and output between uint64 and int64 for optimal performance.

The above is the detailed content of How to Generate Unique Deterministic Integers Without Duplicates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template