Perl Quick Delete Array repeating elements, previously wrote a similar blog, today asked, but the shuffle!

Source: Internet
Author: User
Tags shuffle



I've written a similar blog before: http://blog.csdn.net/three_man/article/details/34084361
Take it out today and take a good look at it:


1. Construct an array containing duplicate elements
 
 
my @arr1 = (1 .. 10);
my @arr2 = (5 .. 15);

# join multi array
my @arr = (@arr1, @arr2);
2. Delete duplicate elements in the array
 
sub removeRepeat
{
    my $arrRef = shift;
    my %count = ();

    my @uniqArr = grep { ++$count{$_} == 1 } @$arrRef;

    return @uniqArr;
}
    • Defines a count hash and initializes it to NULL, which is: my%count = ();
      The hash%count key is an array element (that is, $_ in the code above), and value is a count of the number of repeating elements of the array (that is, $count{$_} in the code above, with an initialization value of 0, And the hash is obtained by key each time value, value will + +)

    • The code block {+ +$count{$_} = = 1} is used as a criterion for non-repeating elements, and a subarray that satisfies the non-repeating element is obtained by grep


Full code:


 
 
#!/usr/bin/perl -w

use strict;
use warnings;
use English;

my @arr1 = (1 .. 10);
my @arr2 = (5 .. 15);

# join multi array
my @arr = (@arr1, @arr2);

printArr(\@arr);
print "-------------------------------------\n";

my @uniqArr = removeRepeat(\@arr);
printArr(\@uniqArr);

# remove repeat element in array
sub removeRepeat
{
    my $arrRef = shift;
    my %count = ();

    my @uniqArr = grep { ++$count{$_} == 1 } @$arrRef;

    return @uniqArr;
}

# print array
sub printArr
{
    my $arrRef = shift;

    foreach my $element (@$arrRef)
    {
        print "$element\n";
    }
}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



Perl shortcut to delete array repeating elements, previously wrote a similar blog, today asked, but the shuffle!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.