<?xml version="1.0" encoding="windows-1252"?>
<node id="463839" title="How to Test if Two Arrays are Ordered in the Same Way" created="2005-06-06 01:44:54" updated="2005-08-12 14:13:05">
<type id="1857">
categorized question</type>
<author id="11732">
QandAEditors</author>
<data>
<keywords>
<keyword rating="">
array</keyword>
<keyword rating="">
order</keyword>
<keyword rating="">
superset</keyword>
</keywords>
<field name="doctext">
This is an attempt to save a thread in SoPW which I thought can be useful for others.&lt;br&gt;&lt;br&gt;  

There are already incredible answers in the thread, so feel free to check in SoPW.&lt;br&gt; 

Please don't misunderstand me. I honestly think this can be useful. I don't mean to boost my XP here, or in that thread which I posted.&lt;br&gt;&lt;br&gt;

Here I wanted to test if an array is of a _same order_ with another, left array is always be greater/superset or equal to the right one. Here is my current code.&lt;br&gt;


&lt;code&gt;
#!/usr/bin/perl -w

# The original code here is constructed 
# thanks to ysth's suggestion  

use strict;
my @AR  = qw(a b c);   # First Case
my @ar  = qw(z a b c); # Second Case

my @ar2 = qw(b a);
my @ar3 = qw(a b);
my @ar4 = qw(a b c);
my @ar5 = qw(z a b c);

print "First case\n";
#                   L     R
print test_ordered(\@ar,\@ar2),"\n"; # Answer:False(0)
print test_ordered(\@ar,\@ar3),"\n"; # Answer:True(1)
print test_ordered(\@ar,\@ar4),"\n"; # Answer:True(1)
print test_ordered(\@ar,\@ar5),"\n"; # Answer:True(1)

print "Second case\n";
print test_ordered(\@AR,\@ar2),"\n"; # Answer: False(0)
print test_ordered(\@AR,\@ar3),"\n"; # Answer: True(1)
print test_ordered(\@AR,\@ar4),"\n"; # Answer: True(1)


sub test_ordered
{
    #test if two arrays are ordered in same way
    #assuming no duplicate and left array is always 
    #be greater/superset or equal to the right one

    #    L    R
    my ($ar1,$ar2)= @_;

    my %h;

    @h{@$ar1} = (0..$#{$ar1});
    my $decision = grep($h{$ar2[$_]} != $_, 0..$#{$ar2}) ? 0 : 1;

   return $decision;
}
&lt;/code&gt;

Currently the code give correct answer for the Second Case. How can I modify it such that it's also correct for the First Case?&lt;br&gt;

Now it prints: 
&lt;code&gt;
First Case:       Second Case:
0                 0
0                 1
0                 1
1
&lt;/code&gt;

The desired answer is:
&lt;code&gt;
First Case:       Second Case:
0                 0
1                 1
1                 1
1
&lt;/code&gt;


&lt;div class="pmsig"&gt;&lt;div class="pmsig-393886"&gt;
Regards,&lt;br&gt;
Edward
&lt;/div&gt;&lt;/div&gt;
&lt;code&gt;</field>
<field name="parent_node">
1824</field>
</data>
</node>
