How to Generate Unique Deterministic Integers from Another Integer?

DDD
Release: 2024-11-21 06:15:09
Original
933 people have browsed it

How to Generate Unique Deterministic Integers from Another Integer?

Generating Unique Deterministic Integers from Another Integer

In the quest to create adeterministic number generation function, our aim is to construct a function where each input number generates a unique corresponding number without any duplicates.

Modular Arithmetic Solution:

The ingenious solution lies in modular arithmetic, particularly the Affine cipher. It employs the transformation formula:

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

where:

  • n represents the range of the allowed integer values (e.g., 2^64 for uint64)
  • s is an arbitrary shift value less than the range
  • m is a coprime (no common factors) with n

For the uint64 range, a non-even value for m is suggested to avoid divisibility by 2.

Example Implementation:

import (
    "fmt"
)

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

    transform := func(p uint64) uint64 {
        return p * m + s
    }

    testValues := []uint64{1, 2, 3, 4, 5}
    for _, v := range testValues {
        fmt.Printf("%v -> %v\n", v, transform(v))
    }
}
Copy after login

This function ensures that for all possible uint64 input values, the generated transformed values are unique.

Adapting for Signed Integers:

For signed integers (int64), the approach remains similar. We convert inputs and outputs between uint64 and int64 to maintain unique mappings:

func signedTransform(p int64) int64 {
    return int64(transform(uint64(p)))
}
Copy after login

By utilizing this deterministic function, developers can generate unique and reproducible numbers from any given input integer, making it an invaluable tool for various applications.

The above is the detailed content of How to Generate Unique Deterministic Integers from Another Integer?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template