rehgb has asked for the wisdom of the Perl Monks concerning the following question:

I have a project where I have users at multiple approval levels. There can be multiple people at the same approval level but if there is a level 3 in a company I need to make sure there is a level 2 and a level 1.

So if I have an array of assigned user's levels:
Example:
Bob is at level 1
Barney is at level 4
Homer is at level 3
Mike is at level 3
Tony is at level 3
Matt is at level 2
Jon is at level 2
JJ is at level 2
@approvals = (1, 4, 3, 3, 2, 2, 2);

I will need to check for the highest level then make sure that all the appropriate lower levels exist. In the example above since there is a level 4 there must be at least one employee assigned to levels 3, 2 and 1.

  • Comment on Check for sequential values in an array that can contain duplicate int values

Replies are listed 'Best First'.
Re: Check for sequential values in an array that can contain duplicate int values
by andye (Curate) on Dec 16, 2001 at 22:20 UTC
    rehgb,

    Here's one way to do it:

    my @a=qw(1 2 3 4 6 3 1); my %h = map {$_=>1} @a; my ($max) = reverse sort keys %h; for (1..$max) { print "gap at $_ \n" unless exists $h{$_} }
    hth,
    andy.
      I have two issues with this line:
      my ($max) = reverse sort keys %h;
      The first is that sort defaults to string sorting (i.e. cmp) which will mess up your order as soon as you get to 10. A better way to write it is:
      my ($max) = sort {$b <=> $a} keys %h;
      The second issue is that sorting is an expensive way to find the maximum element. Granted its not bad for small numbers (and this example uses small numbers indeed) To find the maximum number in a set of positive reals, I would use:
      my $max = 0; $max < $_ and $max = $_ for @a;
      This finds the maximum element in one pass through the data.

      -Blake