Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pseudo-random-looking one-to-one int32->int32 function

I am looking for a int32->int32 function that is

  • bijection (one-to-one correspondence)
  • cheap to calculate at least in one direction
  • transforms the increasing sequence 0, 1, 2, 3, ... into a sequence looking like a good pseudo-random sequence (~ half bits flip when argument changes by a small number, no obvious patterns)
like image 413
Vladimir Reshetnikov Avatar asked Mar 20 '13 20:03

Vladimir Reshetnikov


2 Answers

Multiply by a large odd number and xor with a different one.

Bijection: odd numbers have a multiplicative inverse modulo powers of two, so the multiplication is undone by a multiplication by the inverse. And xor is, of course, undone by another xor.

This is basically how the linear congruence pseudo random number generator works.

like image 183
Joni Avatar answered Sep 25 '22 08:09

Joni


Probably an overkill for this task, but have you consider applying any crypto pseudo random permutation or other primitives comes from block ciphers. For example, it may be done using des with known key in counter mode:

younumber xor (des (key, number counter))
like image 20
mstyura Avatar answered Sep 25 '22 08:09

mstyura