Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Count of HoA elements

by ikegami (Patriarch)
on Jan 19, 2007 at 20:15 UTC ( [id://595569]=note: print w/replies, xml ) Need Help??


in reply to Count of HoA elements

should do it

No, it shouldn't. @{...} expects that ... retunrns a reference to an array. values %hash does not.

anyway short of iterating through the entire hash.

What do you think values does? Returns a list obtained by iterating through the entire hash.

And whatever processes the list returned by value has to iterate over that list.

These work:

# time = O(N) memory = O(N*M) my $count = map @$_, values %h;
# time = O(N) memory = O(N) my $count = sum map { scalar @$_ } values %h;
# time = O(N) memory = O(N) my $count = 0; $count += @$_ for values %h;
# time = O(N) memory = O(1) my $count = 0; while (my ($k, $v) = each(%h)) { $count += @$v; }

Update:
Added 2nd and 4th solution.
Added time and memory analysis.
Choose the one that's the most readable and maintainable within your speed and memory requirements.

Replies are listed 'Best First'.
Re^2: Count of HoA elements
by Jenda (Abbot) on Jan 19, 2007 at 20:34 UTC

    Though I would not recomend using the second on big datastructures as it builds a list of all the elements in the arrays in the hash. Use either the first solution or

    use List::Util qw(sum); my $count = sum map scalar(@$_), values %h; #or # my $count = sum( map scalar(@$_), values(%h)); # or # my $count = sum( map {scalar(@$_)} values(%h)); # if that syntax looks more readable to you.

    Regarding the update: the first solution uses O(N) of memory where N is the number of elements of the hash, the second O(N*M) where M is the average length of the array in the hash. The List::Util solution is also O(N) memorywise.

Re^2: Count of HoA elements
by BrowserUk (Patriarch) on Jan 19, 2007 at 20:29 UTC

      He asked for the number of elements in the HoA. I took that to mean 5 for the following structure:

      my %h = ( k1 => [ qw( a b c ) ], k2 => [ qw( d e ) ], );

      Your solution simply returns the number of elements in a hash. It could be that's what he meant, but that's now how I interpreted his question.

      This is wrong.

      Not so hasty on the wrong. Fletch and Jenda also interpreted the question like I did.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://595569]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-03-19 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found