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