http://qs321.pair.com?node_id=929865


in reply to Re: Tracking minimum of values in an array over time
in thread Tracking minimum of values in an array over time

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$..$/