Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate code from id using a 1-1 function

Is there any good invertible 1-1 function that maps an integer to another integer? for eg, given the range 0-5, I want to find one that maps:

0->3
1->2
2->4
3->5
4->1
5->0

Also, the mapping should look random.

like image 711
boh Avatar asked Oct 29 '25 06:10

boh


1 Answers

You can fill an array in ascending order and shuffle it. This will usually perform reasonably well, if not being the most efficient memorywise.

You can also rely on a closed discrete transformation, such as multiplication. If you have 2 numbers, P and K, then (I think) as long as P and K are coprime, P^n mod K will produce a nonrepeating, pseudorandom sequence of values of length (K - 1), ranging from 1 to K. This particular manifestation of discrete math is one of the premises of cryptography. Going backwards from sequence to exponent is known as the discrete logarithm problem and is the reason traditional RSA is secure.

You asked for a reversible algorithm. If you keep track of the exponent, you can go from P^n mod K to P^(n-1) mod K without much difficulty. You can take a few shortcuts to go backwards from power to exponent that don't work in cryptography because certain parameters of the algorithm are intentionally discarded to make it harder.

That said, if you happen to break RSA by solving the discrete log problem while you're working on this, be sure to let me know.

like image 77
Wug Avatar answered Nov 01 '25 14:11

Wug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!