in reply to Removing certain elements from an array
The reason for the sort is that it starts dropping elements from the end of the array. If you start from the beginning, you won't drop the elements that you want to drop. Say you want to drop the elements at indices 0 and 2; you drop the element at index 0, but then the other elements squish towards the front of the array. So element 2 is now element 1. So you'll drop the wrong elements. That's why you should start from the end.splice @array, $_, 1 for sort { $b <=> $a } @indices;
Update: tilly pointed out a bug where duplicate indices could lead to dropping incorrect elements in the array. Here's a fix:
This is just getting silly in terms of the number of times we're looping over the data; but it does still seem to be quite fast. Faster than I would have expected, in fact.my %u; splice @array, $_, 1 for grep !$u{$_}++, sort { $b <=> $a } @indices;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE (tilly) 2: Removing certain elements from an array
by tilly (Archbishop) on Aug 25, 2000 at 00:20 UTC | |
|
RE: Re: Removing certain elements from an array
by Anonymous Monk on Aug 24, 2000 at 20:58 UTC |