ajdelore has asked for the wisdom of the Perl Monks concerning the following question:
I am using the good old fisher-yates shuffle from perlfaq4:
my $ref = \@list; for (my $i = @$ref; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$ref[$i,$j] = @$ref[$j,$i]; } # @list is modified in place
Question: why do I have to use a reference? I can't figure this out. I tried:
for (my $i = scalar(@list); --$i; ) { my $j = int rand ($i+1); next if $i == $j; @list[$i,$j] = @list[$j,$i]; }
This didn't work... Some elements were duplicated in the changed list. This is probably just a lack of understanding references well, but could some monk please explain this?
</ajdelore>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Why do I need to shuffle an array by reference?
by revdiablo (Prior) on Aug 13, 2003 at 23:41 UTC | |
|
Re: Why do I need to shuffle an array by reference?
by Zaxo (Archbishop) on Aug 13, 2003 at 23:24 UTC | |
|
Re: Why do I need to shuffle an array by reference?
by BrowserUk (Patriarch) on Aug 13, 2003 at 23:47 UTC | |
|
Re: Why do I need to shuffle an array by reference?
by Abigail-II (Bishop) on Aug 14, 2003 at 07:42 UTC | |
|
Re: Why do I need to shuffle an array by reference?
by ajdelore (Pilgrim) on Aug 14, 2003 at 16:33 UTC |