in reply to Returning the lowest key in a hash (or highest)
Yes indeed, this required considerably more code than I had anticipated...
update: Added tilly's optimization (doh!), so now delete's are overall an O(1) operation. Just don't go deleting the keys in sorted order :)
update2: Added dkubb's optimization to _min and _max routines... good call!
use strict; package MinMaxHash; sub HASH () { 0 }; sub MIN () { 1 }; sub MAX () { 2 }; sub new { my $class = shift; my $self = bless {}, $class; tie %$self, $class; $self; } sub minkey { my $self = shift; (tied %$self)->[MIN]; } sub maxkey { my $self = shift; (tied %$self)->[MAX]; } sub TIEHASH { bless [], shift; } sub STORE { my ($self, $key, $val) = @_; $self->[HASH]{$key} = $val; if (!defined $self->[MIN] or $key < $self->[MIN]) { $self->[MIN] = $key; } if (!defined $self->[MAX] or $key > $self->[MAX]) { $self->[MAX] = $key; } } sub FETCH { my ($self, $key) = @_; $self->[HASH]{$key}; } sub DELETE { my ($self, $key) = @_; delete $self->[HASH]{$key}; $self->[MIN] = _min(keys %{$self->[HASH]}) if $key == $self->[MIN]; $self->[MAX] = _max(keys %{$self->[HASH]}) if $key == $self->[MAX]; } sub CLEAR { my $self = shift; $self = []; } sub EXISTS { my ($self, $key) = @_; exists $self->[HASH]{$key}; } sub FIRSTKEY { my $self = shift; () = keys %{$self->[HASH]}; # reset iterator each %{$self->[HASH]}; } sub NEXTKEY { my $self = shift; each %{$self->[HASH]}; } # tilly^H^H^H^H^Hdkubbs's min & max subs... used only during DELETE's sub _max { my $max = shift; $max < $_ and $max = $_ for @_; $max; } sub _min { my $min = shift; $min > $_ and $min = $_ for @_; $min; } ### EXAMPLE ### package main; use Data::Dumper; my $h = new MinMaxHash; $h->{1} = 'foo'; $h->{2} = 'bar'; $h->{3} = 'baz'; $h->{10} = 'goop'; $h->{-1} = 'moo'; print "Minkey is ", $h->minkey, $/; print "Maxkey is ", $h->maxkey, $/; print Dumper $h;
MeowChow s aamecha.s a..a\u$&owag.print
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 2: Returning the lowest key in a hash (or highest)
by tilly (Archbishop) on Mar 25, 2001 at 05:55 UTC | |
|
(dkubb) Re: (3) Returning the lowest key in a hash (or highest)
by dkubb (Deacon) on Mar 25, 2001 at 07:22 UTC | |
by petral (Curate) on Mar 27, 2001 at 06:46 UTC | |
by and (Pilgrim) on Mar 27, 2001 at 20:12 UTC |