How can I generate an array in Perl with 100 random values, without using a loop?
I have to avoid all kind of loops, like \"for\", foreach\", while. This is my exerc
Too bad most of the solutions focused on the non-looping part and neglected the random numbers part:
use LWP::Simple;
my @numbers = split /\s+/, #/ Stackoverflow syntax highlighting bug
get( 'http://www.random.org/integers/?num=100&min=1&max=100&col=1&base=10&format=plain&rnd=new' );
Here's the insanity that Tom was waiting to see, but I make it slightly more insane. This solution reduces the problem to a rand call:
my @numbers = rand( undef, 100 ); # fetch 100 numbers
Normal rand normally takes 0 or 1 arguments. I've given it a new prototype that allows a second argument to note how many numbers to return.
Notice some differences to the real rand though. This isn't continuous, so this has far fewer available numbers, and it's inclusive on the upper bound. Also, since this one takes two arguments, it's not compatible with programs expecting the real one since a statement like this would parse differently in each:
my @array = rand 5, 5;
However, there's nothing particularly special about CORE::GLOBAL::rand() here. You don't have to replace the built-in. It's just a bit sick that you can.
I've left some print statements in there so you can watch it work:
BEGIN {
my @buffer;
my $add_to_buffer = sub {
my $fetch = shift;
$fetch ||= 100;
$fetch = 100 if $fetch < 100;
require LWP::Simple;
push @buffer, split /\s+/, #/ Stackoverflow syntax highlighting bug
LWP::Simple::get(
"http://www.random.org/integers/?num=$fetch&min=1&max=100&col=1&base=10&format=plain&rnd=new"
);
};
my $many = sub ($) {
print "Fetching $_[0] numbers\n";
$add_to_buffer->($_[0]) if @buffer < $_[0];
my @fetched = splice @buffer, 0, $_[0], ();
my $count = @fetched;
print "Fetched [$count] @fetched\n";
@fetched
};
*CORE::GLOBAL::rand = sub (;$$) {
my $max = $_[0] || 1; # even 0 is 1, just like in the real one
my $fetch = $_[1] || ( wantarray ? 10 : 1 );
my @fetched = map { $max * $_ / 100 } $many->( $fetch );
wantarray ? @fetched : $fetched[-1];
};
}
my @rand = rand(undef, 5);
print "Numbers are @rand\n\n";
@rand = rand(87);
print "Numbers are @rand\n\n";
$rand = rand(undef, 4);
print "Numbers are $rand\n\n";
$rand = rand();
print "Numbers are $rand\n\n";
$rand = rand(undef, 200);
print "Numbers are $rand\n\n";
My source of random numbers isn't important for this technique though. You could read from /dev/random or /dev/urandom to fill the buffer if you like.