Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: compare two arrays if both are equal and have same elements irrespective of their position

by davido (Cardinal)
on Jun 16, 2021 at 17:45 UTC ( [id://11133927]=note: print w/replies, xml ) Need Help??


in reply to compare two arrays if both are equal and have same elements irrespective of their position

You should read the documentation for Array::Compare. It's useful. It's written to answer these sorts of questions. I think you simply want to change $comp->compare to $comp->perm. This is in the module's POD. Here's a test example:

#!/usr/bin/env perl use strict; use warnings; use List::Util qw(shuffle); use Array::Compare; my @array1 = shuffle(1..100); my @array2 = shuffle(@array1); my $comp = Array::Compare->new; print "perm: ", $comp->perm(\@array1, \@array2) ? "Same elements\n" : "Different elements\n"; print "compare: ", $comp->compare(\@array1, \@array2) ? "Same elements, same order\ +n" : "Different elements or diff +erent order\n";

The shuffle gives a 1:100! chance of the lists being in the same order, I think. So for this test we can usually assume that the elements start out in dissimilar orders. But we do test for that just to be sure. If we run it the output should be:

perm: Same elements compare: Different elements or different order

So even though the elements come in a different order, the perm() method determines that we got the same elements.


Dave

  • Comment on Re: compare two arrays if both are equal and have same elements irrespective of their position
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: compare two arrays if both are equal and have same elements irrespective of their position
by noviceuser (Acolyte) on Jun 16, 2021 at 17:56 UTC
    thanks a lot, changing to $comp->perm worked.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11133927]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (6)
As of 2024-04-18 14:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found