Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Remove redundency from an array

by lyklev (Pilgrim)
on Sep 24, 2007 at 19:33 UTC ( #640792=note: print w/replies, xml ) Need Help??

in reply to Remove redundency from an array

Most of the answers given involve a hash, which is a good idea; the reason for this is that arrays are good for storing, but not for looking up information - hashes are much better suitable for that. You might want to redesign your program slightly, so you store your information in a hash to start with.

However, since you will be sorting the array, there might be a different approach: first sort it, and since it is sorted, remove duplicate elements, which, because of the sorting, will be sequential.

use strict; use warnings; my @array = (1,2,5,6,4,2,1,2,3,4,6,4,3,2,4,6,6); my @sorted = sort {$a <=> $b} @array; # numerically @array = (sort shift @sorted); # overwrite old array while (my $element = shift @sorted) { # if the element differs from the last added, keep it # otherwise discard if ($element != $array[-1]) { push (@array, $element); } } # array is now sorted, no duplicate elements +

Replies are listed 'Best First'.
Re^2: Remove redundency from an array
by Eimi Metamorphoumai (Deacon) on Sep 25, 2007 at 17:00 UTC
    The idea is sound. Depending on how many duplicates there are, it may end up more expensive (since you're sorting the entire array, instead of only the unique items). Also, the line @array = (sort shift @sorted) is really...odd. Why not just @array = shift @sorted? Additionally, I think instead of while (my $element = shift @sorted) { I would have just used for (@sorted){, unless there's a reason you really want to destroy the sorted version as you go.
      You are right, it should have been just

      @array = (shift @sorted)

      (the parentheses are to make it an array assignment).

      If there are many duplicates it might be more efficient to first remove the duplicates before sorting. But there is no transforming the array into a hash and back.

      I can't tell which is more efficient. My intention was to show a different approach. It shows again that there are many ways to do similar things.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://640792]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2018-07-17 10:00 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (363 votes). Check out past polls.