Re: Randomly outputting an array
- From: "John W. Krahn" <someone@xxxxxxxxxxx>
- Date: Fri, 14 Jul 2006 19:35:47 GMT
Richard Heathfield wrote:
ryanarossi@xxxxxxxxx said:
What would be the simplest way to output an array in random order, but
every element in the array MUST be outputted and the elements cannot
repeat? My current code is below, which I simply have a very large
array and I am outputting windows of an arbitary length.
OPTION BASE 0
DIM DECK(52) AS INTEGER
DIM N AS INTEGER
DIM R AS INTEGER
DIM T AS INTEGER
N = 52
REM Populate array
FOR J = 0 TO N - 1 STEP 1
DECK(J) = J
NEXT
REM Display in original order
FOR J = 0 TO N - 1 STEP 1
PRINT J;" ";
NEXT
REM Shuffle
FOR J = 0 TO N - 1 STEP 1
R = INT(RND * (N - J)) + J
T = DECK(R)
DECK(R) = DECK(J)
DECK(J) = T
NEXT
REM Display in shuffled order
FOR J = 0 TO N - 1 STEP 1
PRINT J;" ";
NEXT
END
Converting to a sensible language is left as an exercise.
#!/usr/bin/perl
use warnings;
use strict;
sub shuffle {
my $deck = shift;
my $i = @$deck;
while ( $i-- ) {
my $j = int rand( $i + 1 );
@$deck[ $i, $j ] = @$deck[ $j, $i ];
}
}
# Populate array
my @deck = 0 .. 51;
# Display in original order
print "@deck\n";
# Shuffle
shuffle \@deck;
# Display in shuffled order
print "@deck\n";
__END__
John
--
use Perl;
program
fulfillment
.
- Follow-Ups:
- Re: Randomly outputting an array
- From: Richard Heathfield
- Re: Randomly outputting an array
- References:
- Randomly outputting an array
- From: ryanarossi@xxxxxxxxx
- Re: Randomly outputting an array
- From: Richard Heathfield
- Randomly outputting an array
- Prev by Date: Re: What language for mathematical applications?
- Next by Date: Re: What language for mathematical applications?
- Previous by thread: Re: Randomly outputting an array
- Next by thread: Re: Randomly outputting an array
- Index(es):
Relevant Pages
|