in reply to Re: Data structure challenge
in thread Data structure challenge
I came up with something similar using a hash to emulate a sparse array
#! perl -slw use strict; local $, = ' '; my( $A, $B, $C ) = ( {}, [], 0 ); sub query{ my $i = shift; return ( exists $A->{ $i } and 0 <= $A->{ $i } and $A->{ $i } < $C + and $B->[ $A->{ $i } ] == $i ) ? 1 : 0; } sub insert{ my $i = shift; if( !query( $i ) ) { $B->[ $C ] = $i; $A->{ $i } = $C; $C++ } } sub del{ my $i = shift; if( query( $i ) ) { my $a = $A->{ $i }; my $b = $B->[ --$C ]; $B->[ $a ] = $b; $A->{ $b } = $a; } } sub clear{ $C = 0; } my @numbers = map{ int rand( 2**16 ) } 1 .. 10; print 'Query before insert'; printf "%5d : %s\n", $_, query( $_ ) for @numbers; insert $_ for @numbers; print "\nQuery after insert"; printf "%5d : %s\n", $_, query( $_ ) for @numbers; del $_ for @numbers[ 0..4 ]; ## Delete half print "\nQuery after deleting half"; printf "%5d : %s\n", $_, query( $_ ) for @numbers; del $_ for @numbers; ## Delete them all regardless if they still exist +s print "\nQuery after deleting the rest"; printf "%5d : %s\n", $_, query( $_ ) for @numbers;
But then realised that I might as well just use the hash to start with and save all the bother. Besides, the hash scalaes better. The overhead of allocating 4GB of ram in order to allocates 3 unique 32-bit integers (for example) is far higher than hashing those 3 integers.
|
|---|