ViceRaid has asked for the wisdom of the Perl Monks concerning the following question:
Afternoon
I'm looking for something that works like a hash, but whose keys are ranges of integers. When I want a value from a hash, I give it a single integer, and it should return the value whose range key includes the given integer. Here's an implementation:
package RangedHash; sub TIEHASH { bless({}, shift); } # the key should be the start point of the range sub STORE { $_[0]->{$_[1]} = $_[2]; } sub FETCH { my ($self, $point) = @_; my $cursor = 0; foreach ( sort keys %$self ) { return $self->{$cursor} if ( $point >= $cursor && $point < $_ +); $cursor = $_; } return $self->{$cursor} } package main; my %ranged_hash; tie(%ranged_hash, "RangedHash"); $ranged_hash{0} = 'foo'; $ranged_hash{10} = 'bar'; $ranged_hash{20} = 'qux'; $range_hash{3}; # 'foo' $range_hash{14}; # 'bar' $range_hash{27}; # 'qux'
However, for high values, it has to look through every other key first, which rather defeats the point of hashes. In the real application, I'm working with these ranged hashes with hundreds or thousands of pairs. I'm wondering if there's a better algorithm, or prior art here? It doesn't necessarily have to work with tie, btw.
(If it's of interest, I'm working with long strings in a GUI that are composed of fragments of other strings. Some of the time, I need to be able to work out for a given point in the long composite string where the original fragment came from.)
Update: I should have stated that the ranges are:
TIA,
alex
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Hash keyed on ranges
by ColonelPanic (Friar) on May 07, 2004 at 13:04 UTC | |
by ViceRaid (Chaplain) on May 07, 2004 at 13:10 UTC | |
Re: Hash keyed on ranges
by BrowserUk (Patriarch) on May 07, 2004 at 13:14 UTC | |
by ViceRaid (Chaplain) on May 07, 2004 at 13:28 UTC | |
by BrowserUk (Patriarch) on May 07, 2004 at 14:06 UTC | |
Re: Hash keyed on ranges
by Limbic~Region (Chancellor) on May 07, 2004 at 13:56 UTC | |
Re: Hash keyed on ranges
by dragonchild (Archbishop) on May 07, 2004 at 13:09 UTC | |
by ColonelPanic (Friar) on May 07, 2004 at 14:05 UTC | |
Re: Hash keyed on ranges
by ysth (Canon) on May 07, 2004 at 16:13 UTC |