http://qs321.pair.com?node_id=651240


in reply to Load Balancing

It has to be remembered that random is not the same as 'no repeat'. Truly random sequences will have long strings of identical repeats. To compensate, you'll need some logic to avoid the previous guess. As an example:

#!/usr/bin/perl use warnings; use strict; my @server_list = ( 'server1', 'server2', 'server3', 'server4' ); my @picked = ( 0,0,0,0 ); my $picks = shift; foreach ( 1 .. $picks ) { my $i = int(rand( scalar @server_list )); print "Guess = $i\n"; while ( $picked[$i] ) { $i = int(rand ( scalar @server_list )); print "Guess = $i\n"; }; for my $j ( 0 .. $#server_list ) { if ( $j == $i ) { $picked[$j] = 1; } else { $picked[$j] = 0; } } print "Chosen => ", $i, "\n"; }
And a sample set of results are:

C:\Code>perl no_repeats.pl 5 Guess = 1 Chosen => 1 Guess = 3 Chosen => 3 Guess = 1 Chosen => 1 Guess = 1 Guess = 1 Guess = 0 Chosen => 0 Guess = 0 Guess = 0 Guess = 3 Chosen => 3
In the case of a script which runs from scratch each time, it will need some kind of external access to not repeat itself. That could be a file that keeps a number or name of the last called server, or it could be a randomizing daemon that is persistent and is called by the nonpersistent script. It could be a fifo that is set up initially (if it does not exist) and is read by the script before executing a new random number. Once a random number is used, write it into the fifo.

Update: Added comments on persistence mechanisms.