This would seem like an easy problem, but I'm not finding it to be as easy as expected.
Briefly, I would like to take an array and shuffle its elements.
However,
sort { int(rand(2))?1:-1 } doesn't do what I want, as the following program demonstrates:
for $r (0..5000) {
@a=sort { int(rand(2))?1:-1 } (0..9);
($g)=grep($a$_==4,(0..9));
$h{$g}++;
}
for $r (0..9) {print "$r $h{$r}\n";}
As you can see if you run this, the element originally in the fifth position has a much larger chance of staying put or of moving only slightly than it should if the list were truly randomly shuffled.
One thought I've had would be to start with a list of indices and randomly pick one at a time, something like:
@b=(0..9); @a=();
while(@b) {$i=int(rand($#b+1)); push @a, splice(@b,$i,1);}
Unfortunately, this seems awfully slow.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.