How to Generate Deterministic and Unique Integers from Input Numbers?

Barbara Streisand
Release: 2024-11-23 08:38:50
Original
830 people have browsed it

How to Generate Deterministic and Unique Integers from Input Numbers?

Deterministic and Unique Number Generation

Given the need to generate deterministic integers that map uniquely to each input number, it may seem like an impossibleЗадача. However, there is a mathematical formula that can fulfill this requirement.

Transformation Formula

The transformation formula is derived from modular arithmetic:

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

where:

  • P is the input number
  • m is a non-even number coprime with n
  • s is a random number less than n
  • n is the range of values to be generated (e.g., 2^64 for uint64)

This formula ensures that every input P maps to a unique output in the range 0 to n-1. The coprimality condition for m prevents common factors between m and n, eliminating periodic patterns and collisions.

Implementation Example for uint64

For a uint64 range, the following parameter values can be used:

var (
    m = uint64(39293)
    s = uint64(75321908)
)

func transform(p uint64) uint64 {
    return p*m + s
}
Copy after login

Extension to int64

For signed numbers (int64), a similar approach can be used. The original transformation for uint64 is applied after converting the input and output to and from uint64:

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

By utilizing this deterministic and unique number generation scheme, it becomes possible to map input numbers to unique outputs without requiring an array or memory-intensive sorting.

The above is the detailed content of How to Generate Deterministic and Unique Integers from Input Numbers?. 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