Home > Backend Development > Golang > How to Generate Unique, Deterministic Numbers with a 1:1 Mapping?

How to Generate Unique, Deterministic Numbers with a 1:1 Mapping?

Barbara Streisand
Release: 2024-11-17 18:30:03
Original
1046 people have browsed it

How to Generate Unique, Deterministic Numbers with a 1:1 Mapping?

Constant Deterministic Number Generation with 1:1 Mapping

Objective

Generate a deterministic function that maps input numbers to unique output numbers within a specified range, without duplication.

Method

Utilize modular arithmetic based on the Affine cipher:

  1. Transformation Formula: f(P) = (mP s) mod n
  2. Parameters:

    • m: Must be coprime with n (not divisible by the same numbers as n).
    • s: A random number less than n.
    • n: The desired range of the output.

Example for uint64

  • n = 2^64 (uint64 range)
  • m = 39293 (an odd number)
  • s = 75321908 (random number < 2^64)

Transformation Function:

func transform(p uint64) uint64 {
    return m * p + s  // implicitly mod'd 2^64 by the type's size
}
Copy after login

Example with int64

For signed numbers, convert input and output between uint64 and int64 to maintain the unique mapping:

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

Guarantees

  • The function ensures a 1:1 mapping for all input numbers.
  • No two input numbers will generate the same output number.
  • The output numbers will be uniformly distributed within the specified range.
  • The function is deterministic, always generating the same output for a given input.

The above is the detailed content of How to Generate Unique, Deterministic Numbers with a 1:1 Mapping?. 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