mojodaddy has asked for the wisdom of the Perl Monks concerning the following question:
Let's say I have 10 widgets:
my @widgets = qw( foo bar baz blort blah plugh xyzzy arfle barfle gloop );
I need to have 3 of them running all the time, but they get tired and need to rest, so when I start my day I pick the three most rested and put them to work, and then when one gets tired I need to replace it with the next most rested one that isn't already running. They all have different "rest" values, and they tire and rejuvenate at different rates, so the most rested one now might not be the most rested one later. But that's OK because whenever I need one I can just do a database query that will rank them in order of most rested, 2nd most, etc. Unfortunately, it won't tell me if the most rested bugger is already running or not.
So lets say I start the day with:
my @running = qw(foo bar baz);
After a while foo gets tired and needs a break. The next widget in the queue is $w. So, what is the best way to check whether $w is an element of @running?
Currently I have something like:
# get the top 3 candidates from the db while (my $wref = $sth->fetchall_arrayref([0], 3)){ my $w = $wref->[0]; foreach my $r (@running){ unless ($r eq $w){ # put $w to work } else{ # try the next $w } } }
Which is fine, I guess, since I only have to check at most two elements against 9 or 10 or whatever; but it seems to me that once we get into bigger numbers, that technique could take months!
From what I read about slices it seemed I'd need to know what position the element had in the array. I experimented with sort and got really confused, and once I read How to compare arrays? (xmms alarm clock) and Array::Compare I started to realize that maybe this wasn't as simple a problem as I thought.
If anyone has some magic to share on this, I'd sure appreciate it.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: comparing array elements
by jdporter (Paladin) on Mar 30, 2007 at 15:31 UTC | |
by mojodaddy (Pilgrim) on Mar 30, 2007 at 15:49 UTC | |
by pileofrogs (Priest) on Mar 30, 2007 at 16:50 UTC | |
by mojodaddy (Pilgrim) on Mar 30, 2007 at 17:08 UTC | |
by jdporter (Paladin) on Mar 30, 2007 at 19:50 UTC | |
by mojodaddy (Pilgrim) on Mar 30, 2007 at 20:25 UTC | |
|
Re: comparing array elements
by andye (Curate) on Mar 30, 2007 at 15:32 UTC |