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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.