[LON-CAPA-users] Choosing m elements out of n in an array
Guy Ashkenazi
lon-capa-users@mail.lon-capa.org
Mon, 21 Feb 2005 23:33:19 +0200
I've seen several people using the following method to choose 3
different elements out of n in an array:
=================================
$which1=&random(0,$#reaction,1);
$which2=&random(0,$#reaction,1);
while ($which1 == $which2) {
$which2=&random(0,$#reaction,1)
};
$which3=&random(0,$#reaction,1);
while (($which3 == $which2) || ($which3 == $which1)) {
$which3=&random(0,$#reaction,1)
};
$reaction1=$reaction[$which1];
$answer1=$answer[$which1];
$reaction2=$reaction[$which2];
$answer2=$answer[$which2];
$reaction3=$reaction[$which3];
$answer3=$answer[$which3];
=================================
It is much shorter (and more legible) to use:
$seed=&random(1,1000000,1);
@reaction=&random_permutation($seed,@reaction);
@answer=&random_permutation($seed,@answer);
and then use $reaction[0], $answer[0], $reaction[1], $answer[1],... in
the question. This method can be used for any m <= n, while the
previous one will become more complex to write (and time consuming to
run) as m approaches n.
Question for Guy - is there a difference between using
&random_permutation() and &map() ?
Guy.