http://www.perlmonks.org?node_id=418850


in reply to Comparison by position and value

Update: modified output to display only the original strings as suggested by steves.
Whereas these two would be incompatible
_8__3__19 4_8___7__
because the digit 8 appears in both, but at a different position. And these two are incompatible
_8__3__19 48_____7_
because the second last digit in both strings contains a different value.
The second incompatibility is simple to test for using boolean operations. If we look at the strings as partial permutations, the first incompatibility is equivalent to the second incompatibility on the inverse partial permutations. So maybe a Schwartzian transform is in order. Are all your strings 9 characters long? Are all your digits the numbers 1..9? If so, maybe the following will help:
sub appendinverse { my $string = shift; my @revarray; for my $i (0..8) { $revarray[0+substr($string, $i, 1)] = $i; } delete $revarray[0]; for my $i (1..9) { if(exists $revarray[$i]) { $string .= $revarray[$i]; } else { $string .= "_"; } } return $string; } # test harness stolen from steves my @tests = (qw/ _8__3__19 48____7__ _8__3__19 4_2___7__ _8__3__19 4_8___7__ __8_3__19 48____7__ __8_3__19 84____7__ _8__3__19 48_____7_ / ); # Schwartzian transform for my $i (@tests) { $i = appendinverse $i; # print "$i\n"; } sub compatible { my $a = shift; my $b = shift; # modified as suggested by steves # print "\n$a\n$b\n"; print "\n",substr($a,0,9),"\n",substr($b,0,9),"\n"; if (($a^$b)=~/[\001-\017]/) { print "incompatible\n"; } else { print "compatible\n"; } } # test harness stolen from steves my ($s1, $s2); while (defined($s1 = shift(@tests))) { $s2 = shift(@tests); compatible($s1, $s2); }
which outputs:
_8__3__197_4____18 48____7_____0__61_ compatible _8__3__197_4____18 4_2___7___2_0__6__ compatible _8__3__197_4____18 4_8___7_____0__62_ incompatible __8_3__197_4____28 48____7_____0__61_ incompatible __8_3__197_4____28 84____7_____1__60_ incompatible _8__3__197_4____18 48_____7____0__71_ incompatible
_8__3__19 48____7__ compatible _8__3__19 4_2___7__ compatible _8__3__19 4_8___7__ incompatible __8_3__19 48____7__ incompatible __8_3__19 84____7__ incompatible _8__3__19 48_____7_ incompatible

Replies are listed 'Best First'.
Re^2: Comparison by position and value
by steves (Curate) on Jan 03, 2005 at 02:22 UTC

    Output is a little misleading since it shows the transformed sequences -- not the originals.