[Israel.pm] array 2 hash for quick search

Itamar Elem elem at compugen.co.il
Tue Jun 15 05:00:40 PDT 2004

hi ofer

didnt solution 3 depend on the parity of the array size?

-----Original Message-----
From: Offer Kaye [mailto:oferk at oren.co.il]
Sent: Tuesday, June 15, 2004 3:23 PM
To: Perl in Israel
Subject: RE: [Israel.pm] array 2 hash for quick search

> David and Itamar, thanks.
> This is a lot better! :-)
> --
> Shlomo Yona

The 2 solutions suggested for now have been:
1)   my %hash = map { $_, 1 } @array;
2)   my %hash; $hash{$_}++ for @array;

The difference between them is that (1) fills the values with the number 1,
while (2) fills the values with the number of times a key appeared. (1) is
also more elegant :-)
Here are two other possible approaches:

3)   my %hash = (@array,reverse @array);
4)   my %hash; @hash{@array} = (1) x ($#array+1);

Number (3) works since first @array[0,2,4,...] fills the keys of %hash, then
the reversed array makes sure that @array[1,3,5,...] also fill the keys. The
values will be the array values rather than a number, but the value was not
specified by Shlomo as a requirement...
Number (4) is not as elegent, IMHO, as the others, I've added it just for
completeness. I also suspect it may be a little faster than (1) or (2) in
filling up a hash when the array is large, but I'm not sure.

I'm curious - can anybody think of additional inventive ways to do this? :-)

Offer Kaye

Perl mailing list
Perl at perl.org.il

More information about the Perl mailing list