Woops! Should have placed greater focus on the word _establish_. To speed things up, I furnish the details of the function (in this case, $x
$i within the "function" bit at the end), instead of re-evaluating it every time I call a subroutine. So, to clarify, say I use two subroutines, choose_weighted and weight_array.
my $etc = 0;
my @x = (1.3, 1.4, 900, .03, 7, $etc, $etc);
@x = weight_array(@x);
my $random_value = choose_weighted(@x);
sub weight array {
my @x = @_;
my $y = 0;
my $i = 0;
until ($i > $#x) {
$y = $y + $x[$i];
$i = $i + 1;
}
$x[0] = $x[0] / $y;
$i = 1;
until ($i > $#x) {
$x[$i] = $x[$i - 1] + $x[$i] / $y;
$i = $i + 1;
}
return @x;
}
sub choose_weighted {
my $y = rand();
my $i = 0;
until ($y < $x[$i]) {
$i = $i + 1;
}
return $i;
}