in reply to Remove array elements dynamically!
While many answers have been given above, every one of them is a quadratic-time solution (Update: Oops! didn't see throop's solution, which is also linear time as pointed out by ikegami. I guess I was writing while throop was posting.). The first removal shifts the top elements of the array down by 1. The next shifts more (including shifting the same previous elements once again), ...). On the other hand these operations are fast enough, that clarity and elegance of code may be reasons enough to not worry about efficiency.
While not as elegant as the previous entries, here is a linear time solution (I am assuming that @arrayindex is a reverse sorted & unique'd list. If not, use Grandfather's technique in Re^4: Remove array elements dynamically! (reverse)). At the end of the loop, the answer is stored in @newarray and @array is empty.
Note that while we are not doing this inplace, there is no memory hit, because the @newarray grows, just as @array shrinks.my @newarray = (); foreach my $i (@arrayindex) { unshift @newarray, (splice @array, $i); pop @array; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Remove array elements dynamically!
by ikegami (Patriarch) on Aug 28, 2007 at 02:12 UTC |