Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Bidirectional lookup algorithm? (Updated: further info.)

by ikegami (Patriarch)
on Jan 05, 2015 at 16:04 UTC ( [id://1112206]=note: print w/replies, xml ) Need Help??


in reply to Bidirectional lookup algorithm? (Updated: further info.)

So you have something like the following:

my $addr = 0x1234; my $ident = "abc"; my %by_addr = ( $addr => $ident ); my %by_ident = ( $ident => $addr );

A copy of the address and of the identifier are stored in the elements of each hash. (The key of an element is stored in the element to distinguish elements in collisions.) You can cut the number of scalars (or is it string buffers?) in half as follows:

use Data::Alias qw( alias ); sub find_undef_element { my ($hash) = @_; while (my ($key, $val) = each(%$hash)) { if (!defined($val)) { keys(%$hash); # Reset iterator. return $key; } } return undef; } my $addr = 0x1234; my $ident = "abc"; my %by_addr; my %by_ident; $by_addr{$addr} = undef; $by_ident{$ident} = undef; alias my $shared_addr = find_undef_element(\%by_addr); alias my $shared_ident = find_undef_element(\%by_ident); alias $by_addr{$shared_addr} = $shared_ident; alias $by_ident{$shared_ident} = $shared_addr;

Of course, constructing is going to be much slower. I think you can avoid iterating through the hash (and avoid using Data::Alias) by dropping to C, but if you can do that, you could use a C-based data structure and use strings instead of scalars.

Update: It seems that only the string buffers are getting shared, not the entire scalar.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-03-28 18:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found