bioplanet has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks! I have a question concering arrays.. Say I have the following array:
(1,12)
(1,13)
(2,14)
(2,15)
(2,3)
(2,16)
(3,15)
(3,3)
(3,20)
(3,5)
(3,6)
(3,20)
Everything is OK except that pair (3,20) is repeated twice. How can I avoid it? 'Map' function is the answer?

2006-01-26 Retitled by g0n, as per Monastery guidelines
Original title: 'map function?'

Replies are listed 'Best First'.
Re: finding duplicates in an array
by Roy Johnson (Monsignor) on Jan 26, 2006 at 16:00 UTC
      Hi, thanx to both of you! I have made a mistake in my question.. what i have is an array of arrays that i want to make unique. That is, I have:
      @AoA=(["1","15"], ["2","5"], ["3","4"], ["3","5"], ["3","8"], ["3","5"], ["4","6"], ["4","5"])
      and I want to remove array element ["3","5"] which is seen twice if you notice. Is that possible?

        You just need to be a bit cleverer about the keys in your %seen hash.

        #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @AoA=(["1","15"], ["2","5"], ["3","4"], ["3","5"], ["3","8"], ["3","5"], ["4","6"], ["4","5"]); my %seen; @AoA = grep { ! $seen{join $;, @$_}++ } @AoA; print Dumper \@AoA;
        --
        <http://dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

Re: finding duplicates in an array
by EvanK (Chaplain) on Jan 26, 2006 at 15:54 UTC
    to clarify, I assume you're using a multi-dimensional array, where each element contains another two-element array?
    $array[0] = [1,12]; $array[1] = [1,13]; $array[2] = [2,14]; #etc...
    or are these literal strings?
    $array[0] = "(1,12)"; $array[0] = "(1,13)"; $array[0] = "(2,14)"; #etc...

    __________
    Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
    - Terry Pratchett

Re: finding duplicates in an array
by planetscape (Chancellor) on Jan 27, 2006 at 14:17 UTC
Re: finding duplicates in an array
by Anonymous Monk on Feb 04, 2008 at 23:24 UTC

    Hey. I have a question really similar to this one:
    Let's say I have an array with:

    (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (2, 3) (2, 3) (4, 1) (5, 1)

    If I wanted to get rid of duplicates of (x, y) AND get rid of any duplicates of the reverse (y, x), how would I best do this?
    ie, I want to end up with:

    (1, 1) (1, 2) (1, 3) (1, 4) or (4, 1) (1, 5) or (5, 1) (2, 3)

    Really appreciate any suggestions! Thanks!

      If the order of the elements in each (x, y) pair really doesn't matter, then sorting them should result in data that can then be processed using the techniques in finding duplicates in an array. In other words, make both (1, 4) and (4, 1) into the same pair.

      Was that enough of a hint, or do you need an example?

      Update: I couldn't resist.

      my @aoa = ( [1,4], [4,1] ); my @sorted = map { [ sort { $a <=> $b } @$_ ] } @aoa;