Thank you all for your replies.

I tested the 5 solutions with the benchmark module, and the splice one
is the fastest:

Benchmark: timing 999999 iterations of each, grep, hash, keep, splice...
 each:  5 wallclock secs ( 5.07 usr +  0.00 sys =  5.07 CPU) @
197238.46/s (n=999999) 

 grep:  5 wallclock secs ( 4.96 usr +  0.00 sys =  4.96 CPU) @
201612.70/s (n=999999) 

 hash:  6 wallclock secs ( 5.37 usr +  0.00 sys =  5.37 CPU) @
186219.55/s (n=999999) 

 keep:  2 wallclock secs ( 1.68 usr +  0.00 sys =  1.68 CPU) @
595237.50/s (n=999999)

splice:  1 wallclock secs ( 1.40 usr +  0.00 sys
=  1.40 CPU) @ 714285.00/s (n=999999)


The hash one, which was my first solution is the slowest one. :-(

code and results: https://pastebin.com/FYdJzVzu

Thanks all.

Regards,
David Santiago


On Wed, 12 Apr 2017 16:50:49 -0400
Uri Guttman <u...@stemsystems.com> wrote:

> On 04/12/2017 04:38 PM, Shlomi Fish wrote:
> > Hi Uri!
> >
> > Some notes.
> >
> > On Wed, 12 Apr 2017 15:19:33 -0400
> > Uri Guttman <u...@stemsystems.com> wrote:
> >  
> >> On 04/12/2017 03:00 PM, David Emanuel da Costa Santiago wrote:  
> >>> Hello!
> >>>
> >>> What's the best way to delete multiple indices from an array?
> >>>
> >>> i'm doing:
> >>>
> >>> ---------------
> >>> my @array=qw/zero one two three four five six seven eight nine
> >>> ten/;
> >>>
> >>> my @indicesToDelete = (2,4,6,7);  
> >> if you have the indexes to keep, this would be a simple slice:
> >>
> >> my @keep_indexes = ( 0, 1, 3, 5, 8,9 10 );
> >> @array = @array{ @keep_indexes } ;
> >>  
> > it should be «@array = @array[ @keep_indexes ] ;» instead. With
> > curly braces it's a hash slice.
> >  
> >> so one idea is to make that list of kept indexes from the list of
> >> indexes to delete:
> >>
> >> my %keep_hash ;
> >> @keep_hash{ 0 .. 10 } = () ; # no need for any values so this save
> >> space delete @keep_hash{ @keep_indexes } ;
> >> @array = @array{ keys %keep_hash } ;  
> > 1. again - square brackets instead of curly braces.  
> yes, i missed that.
> >
> > 2. You should sort the keys numerically using sort { $a <=> $b }.  
> i don't sort the indexes. that was some other code.
> >
> > 3. Better use « keys@array» or in older perls «0 .. $#array» to
> > avoid hard coding the values and magic constants.  
> again, that wasn't my code.
> 
> > ============
> >
> > some other ways I can think of doing it:
> >
> > 1.
> >
> > my %blacklist;
> > @blacklist{@remove} = ();
> > @array = @array[grep {!exists $blacklist{$_} } keys@array];
> >
> > 2.
> >
> > my @new;
> > while (my ($i, $v) = each@array)
> > {
> >     if (@remove and $i == $remove[0])
> >     {
> >             shift@remove;
> >     }
> >     else
> >     {
> >             push @new, $v;  
> >     }
> > }
> > @array = @new  
> that is a much slower version of your grep solution.
> 
> uri
> 

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to