Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 204
  • Last Modified:

Duplicates

What is the most efficient way to strip duplicates from an array?
0
IsleOfView
Asked:
IsleOfView
1 Solution
 
b2piCommented:
perldoc perlfaq4

     a) If @in is sorted, and you want @out to be sorted:
 
             $prev = 'nonesuch';
             @out = grep($_ ne $prev && ($prev = $_), @in);
 
         This is nice in that it doesn't use much extra memory,
         simulating uniq(1)'s behavior of removing only adjacent
         duplicates.
 
     b) If you don't know whether @in is sorted:
 
             undef %saw;
             @out = grep(!$saw{$_}++, @in);
 
     c) Like (b), but @in contains only small integers:
 
             @out = grep(!$saw[$_]++, @in);
 
     d) A way to do (b) without any loops or greps:
 
             undef %saw;
             @saw{@in} = ();
             @out = sort keys %saw;  # remove sort if undesired
 

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now