M
Mei
Hi,
I want to generate 6 random numbers from 1 to 10.
The 6 numbers must not the same.
These numbers must match to the number of an array.
I like to know how many iterations to get the match.
I am having troubles with the do-until loop. Could someone point out the
problem for me?
#!/usr/bin/perl -w
# generate 6 random numbers (1~10) that match exactly to the @ticket
# count the number of loops
use strict;
srand(time||$$);
my @ticket = sort (2, 3, 5, 7, 8, 10);
my @all_number = ();
my @new_number = ();
my $count = 0;
# generate 10 numbers
for (my $i = 0; $i < 10; $i++) {
my $number = $i + 1;
push (@all_number, $number)
}
do {
#reset @new_number to the empty array each time through the loop.
@new_number = ();
#get 6 random numbers
for (my $i = 0; $i < 6; $i++) {
my $position = randomposition (@all_number);
# Pick a random number from @all_number
my $number = splice (@all_number, $position, 1);
push (@new_number, $number);
}
@new_number = sort (@new_number);
print "@new_number\n";
$count++;
} until (($new_number[0] eq "$ticket[0]") && ($new_number[1] eq
"$ticket[1]")
&& ($new_number[2] eq "$ticket[2]") && ($new_number[3] eq
"$ticket[3]")
&& ($new_number[4] eq "$ticket[4]") && ($new_number[5] eq
"$ticket[5]"));
print $count, "\n";
##########################################################
sub randomposition {
my(@all_number) = @_;
# This expression returns a random number
return int(rand(scalar(@all_number)));
}
I want to generate 6 random numbers from 1 to 10.
The 6 numbers must not the same.
These numbers must match to the number of an array.
I like to know how many iterations to get the match.
I am having troubles with the do-until loop. Could someone point out the
problem for me?
#!/usr/bin/perl -w
# generate 6 random numbers (1~10) that match exactly to the @ticket
# count the number of loops
use strict;
srand(time||$$);
my @ticket = sort (2, 3, 5, 7, 8, 10);
my @all_number = ();
my @new_number = ();
my $count = 0;
# generate 10 numbers
for (my $i = 0; $i < 10; $i++) {
my $number = $i + 1;
push (@all_number, $number)
}
do {
#reset @new_number to the empty array each time through the loop.
@new_number = ();
#get 6 random numbers
for (my $i = 0; $i < 6; $i++) {
my $position = randomposition (@all_number);
# Pick a random number from @all_number
my $number = splice (@all_number, $position, 1);
push (@new_number, $number);
}
@new_number = sort (@new_number);
print "@new_number\n";
$count++;
} until (($new_number[0] eq "$ticket[0]") && ($new_number[1] eq
"$ticket[1]")
&& ($new_number[2] eq "$ticket[2]") && ($new_number[3] eq
"$ticket[3]")
&& ($new_number[4] eq "$ticket[4]") && ($new_number[5] eq
"$ticket[5]"));
print $count, "\n";
##########################################################
sub randomposition {
my(@all_number) = @_;
# This expression returns a random number
return int(rand(scalar(@all_number)));
}