There's more than one way to do things PerlMonks

### Re^3: Random 1-1 mapping

 on May 28, 2006 at 21:26 UTC Need Help??

in reply to Re^2: Random 1-1 mapping

A mapping of the form
```f(x) = (a*x + b) % m
is 1-to-1 (restricted to 0 <= x < m) as long as gcd(a,m)==1, since that's the only time you can find an inverse to a mod m, and invert the function.

I would suggest splitting your "seed" value into the a & b coefficients in the following way:

• a = largest number less than seed satisfying gcd(a,m)=1
• b = seed - a
```sub gcd { \$_[1] ? gcd(\$_[1], \$_[0] % \$_[1]) : \$_[0] }

sub shuffle {
my (\$seed, \$max, \$i) = @_;

my \$ca = \$seed;
\$ca-- until gcd(\$ca, \$max) == 1;
my \$cb = \$seed - \$ca;

(\$ca * \$i + \$cb) % \$max;
}

for my \$seed (1 .. 10) {
my @result = map shuffle(\$seed, 15, \$_), 0 .. 14;
print "seed=\$seed ==> @result\n";
}
But take this approach for what it's worth -- The only kinds of mapping you'll get by this process are simple linear (affine) mappings, which may not "look random enough":
```seed=1 ==> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
seed=2 ==> 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13
seed=3 ==> 1 3 5 7 9 11 13 0 2 4 6 8 10 12 14
seed=4 ==> 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11
seed=5 ==> 1 5 9 13 2 6 10 14 3 7 11 0 4 8 12
seed=6 ==> 2 6 10 14 3 7 11 0 4 8 12 1 5 9 13
seed=7 ==> 0 7 14 6 13 5 12 4 11 3 10 2 9 1 8
seed=8 ==> 0 8 1 9 2 10 3 11 4 12 5 13 6 14 7
seed=9 ==> 1 9 2 10 3 11 4 12 5 13 6 14 7 0 8
seed=10 ==> 2 10 3 11 4 12 5 13 6 14 7 0 8 1 9
For more "unpredictable" orders, you could have more tools at your disposal if \$max is always a prime. Then you take one of the linear sequences above and use it as a sequence of powers of a generator element for the field mod \$max.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://552217]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-02-27 02:58 GMT
Voting Booth?
My favourite way to spend a leap day ...

Results (26 votes). Check out past polls.