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
where:
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 }
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))) }
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!