in reply to Repeating an input prompt
Anyway, this code works ...An expression like $positions_ref->[ rand( $#{$positions_ref} ) ] will never evaluate to the last element of the array. Use $positions_ref->[ rand( @{$positions_ref} ) ] instead (unless you want to avoid the last element!).
Updates:>perl -wMstrict -le "my $n = shift || 1000; my $arrayref = [ qw{ a b c d e f g i j k l m n o p } ]; my $last_element = $arrayref->[-1]; my $n_max_i = 0; for (1 .. $n) { my $rand_element = $arrayref->[ rand $#$arrayref ]; ++$n_max_i if $rand_element eq $last_element; } printf 'last element picked randomly %f%% of %d times', $n_max_i/$n*100, $n; " last element picked randomly 0.000000% of 1000 times >perl -wMstrict -le "my $n = shift || 1000; my $arrayref = [ qw{ a b c d e f g i j k l m n o p } ]; my $last_element = $arrayref->[-1]; my $n_max_i = 0; for (1 .. $n) { my $rand_element = $arrayref->[ rand @$arrayref ]; ++$n_max_i if $rand_element eq $last_element; } printf 'last element picked randomly %f%% of %d times', $n_max_i/$n*100, $n; " last element picked randomly 6.700000% of 1000 times
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Repeating an input prompt
by zod (Scribe) on Nov 28, 2008 at 22:09 UTC |