What ++ suaveant said.
I wrote the program below to illustrate how you might do this. Note that you increment your "check" variable (in my program it's called $nfloor) only when an element becomes exactly the "floor" value. You can change the value of $b_slow to zero to make it call the subroutine fast() instead of slow(), and play with the values of $array_size and $floor to see how they affect the overall program speed. ($b_debug, if set, prints out the array each time; you probably only want to do this if $array_size and $floor are both quite small!):
#!/usr/bin/perl -w
# Libraries
use strict;
use warnings;
use 5.010;
# User-defined
my $b_slow = 1;
my $array_size = 3000;
my $floor = 50;
my @array = ( 0 ) x $array_size;
my $b_debug = 0;
# Main program
my $start = time();
while (1) {
# Pick a random index, and increment the corrsponding value
my $idx = int(rand(@array));
# Check all values to see if they've reached $floor
my $b_reached = $b_slow? slow(\@array, $idx): fast(\@array, $idx);
$b_debug and print "@array\n";
$b_reached and last;
}
my $nsecs = time() - $start;
print "Reached floor '$floor' in $nsecs second(s)\n";
# Subroutines
sub slow {
my ($a_array, $idx) = @_;
++$array[$idx];
for (my $i = 0; $i < @$a_array; $i++) {
my $val = $a_array->[$i];
($val < $floor) and return 0;
}
return 1;
}
sub fast {
my ($a_array, $idx) = @_;
state $nfloor = 0;
my $val = ++$a_array->[$idx];
if ($floor == $val) {
++$nfloor;
}
return ($nfloor < $array_size)? 0: 1;
}
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|