Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Re: best data structure

by fruiture (Curate)
on Aug 28, 2002 at 14:29 UTC ( [id://193468]=note: print w/replies, xml ) Need Help??


in reply to Re: best data structure
in thread best data structure

grep will work for this, but it's not a good solution to check for an existing item, especially not via regexp, because it will always iterate over the whole list, even if the elemet is fond at the first position.

So first thought would be a hash again, withe code like that:

our @array = 'a' .. 'e'; our @figure_out = 'd' .. 'g'; { my $index = 0; my %h = map {$_=>$index++} @array; while( my($k,$v) = each %h ){ my $n = shift @figure_out or next; $h{$n} = $index++ unless exists $h{$n}; } @array = sort {$h{$a}<=>$h{$b}} keys %h; }

That may work in special cases, but `perldoc -f each` tells us not to change a hash while iterating over it, so we end up doing it like that:

{ my @new = (); my $in = sub { for(@array,@new){ return 1 if $_ eq $_[0] } return 0 }; local $_; while( @array ){ $_ = shift @array; #this is of course pseufo for really figuring out # a new value my $new = shift @figure_out or next; $in->($new) or push @array,$new; } continue { push @new,$_ } @array = @new; }

An that works.

--
http://fruiture.de

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-24 02:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found