## WeBWorK Problems

### array shuffle woes

by Zak Zarychta -
Number of replies: 1
I have an array shuffle sub routine

# shuffle of @array in place
sub fisher_yates_shuffle {
$array = shift;$i;
for ($i = @$array; --$i; ) {$j = int random(0,$i+1); next if$i == $j; @$array[$i,$j] = @$array[$j,$i]; } } that shuffles the following array of values$ohmD = "{\rm \Omega}";
$ohmU = "ohm";$ampD = "{\rm A}";
$ampU = "amp";$voltD = "{\rm V}";
$voltU = "volt"; @valArr = (# ["V_0",$V_0val,$voltD,$voltU],#
["I_0",$I_0val,$ampD,$ampU],# ["I_1",$I_1val,$ampD,$ampU],#
["I_2",$I_2val,$ampD,$ampU],# ["R_1",$R_1val,$ohmD,$ohmU],#
["R_2",$R_2val,$ohmD,$ohmU]# ); I shuffle the array then pop off the last three sub arrays and push onto another array. This so called unknown array @valArr_unkn contains the values the students are asked to calculate. This is done with the following code fisher_yates_shuffle( ~~@valArr ); # permutes array in place # pop of last three values of known and push onto unknown array @valArr_unkn = ();$size = scalar @valArr_unkn;
while ($size < 3) { @popped = pop(@valArr); push(@valArr_unkn, @popped);$size = scalar @valArr_unkn;
}

whilst this works "most" of the time, for one particular random seed (20109 and I'm sure others), $valArr_unkn[0] and$valArr_unkn[2] contain the four values under the sub-indices 0-3, but the four values of $valArr_unkn[1] are empty leading to errors. What might be wrong? How might I fix it? Thanks in advance for any help with this Regards, Zak In reply to Zak Zarychta ### Re: array shuffle woes by Zak Zarychta - Thankfully, I finally scratched this itch. It came down to a difference in how the perlrand function and the WeBWorK random function treated the right limit. When (from the original perl subroutine) I translated the line #perl$j = int(rand(0,$i+1)); #random number between 0 and$i

to

#WW
$j = random(0,$i+1); #random number between 0 and $i+1 this occasionally (when$i+1 was selected) and would shuffle an empty value onto the array.