superquestions
asked on
random words without repeating
# I have to select three random words three times
@animals=("cat", "rat", "bat");
@unselectedkeys=(0..2);
for(1..9)
{
if(@unselectedkeys==()){@u nselectedk eys=(0..2) };
$randomkey=int rand(@unselectedkeys);
print $animals[$unselectedkeys[$ randomkey] ];
@unselectedkeys=grep{$_!=$ randomkey} @unselecte dkeys;
};
@animals=("cat", "rat", "bat");
@unselectedkeys=(0..2);
for(1..9)
{
if(@unselectedkeys==()){@u
$randomkey=int rand(@unselectedkeys);
print $animals[$unselectedkeys[$
@unselectedkeys=grep{$_!=$
};
ASKER
for(1..9){#instructions}
You can only modify the #instructions.
You can only modify the #instructions.
ASKER
# my debugging efforts
@animals=("cat", "rat", "bat");
@unselectedkeys=(0,1,2);
for(1..9)
{
# reset array when blank
if(@unselectedkeys==()){@u nselectedk eys=(0..2) };
# select a random key
$randomkey=int rand(@unselectedkeys);
# remove the selected key
@unselectedkeys=grep{$_!=$ randomkey} @unselecte dkeys;
};
@animals=("cat", "rat", "bat");
@unselectedkeys=(0,1,2);
for(1..9)
{
# reset array when blank
if(@unselectedkeys==()){@u
# select a random key
$randomkey=int rand(@unselectedkeys);
# remove the selected key
@unselectedkeys=grep{$_!=$
};
ASKER
Why isn't the above script working properly?
try changing
if(@unselectedkeys==()){@u nselectedk eys=(0..2) };
to
if($unselectedkeys[0] eq ""){@unselectedkeys=(0..2) };
if(@unselectedkeys==()){@u
to
if($unselectedkeys[0] eq ""){@unselectedkeys=(0..2)
the problem is that you can get a rand that is not a value in the array...
because you taking the rand on the length an array(1,2) could yeild a rand of 0, but if your array was 1 and 2, then nothing is going to be removed, hence your code fails:
I will see if I can get the grep working, but this is a working solution:
# my debugging efforts
@animals=("cat", "rat", "bat");
@unselectedkeys=(0,1,2);
for(1..9)
{
# reset array when blank
if(@unselectedkeys==()){@u
print @unselectedkeys;
# select a random key
$randomkey=int rand(1+$#unselectedkeys);
# remove the selected key
for($i=0;$i<=$#unselectedk
{
if($i!=$randomkey)
{
push @ok, $unselectedkeys[$i];
}
}
@unselectedkeys=@ok;
$#ok=-1;
};
Bob
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER