0

An array has the following information in its elements

0 ABCD ABDC ACBD ABBC

1 ABCD AAAD ADBC BBAC

2 ABCD CCDB BDCB CABC

I'm trying to write a subroutine that compares each string in each element to other strings in other elements, but I'm sure how to go about doing it. For example, the sub should print that ABCD is be present in all elements. While ABDC is not present in all elements. Thanks for your help.

3
  • 3
    What have you tried thus far? This isn't enough information to fully communicate your intent. Say you have those 3 elements in an array, what EXACTLY would you be desiring as output? Commented Apr 2, 2014 at 21:02
  • I'm assuming the first number is the array element, and not part of its contents? Commented Apr 2, 2014 at 21:06
  • Yup, the numbers in the beginning are the elements Commented Apr 2, 2014 at 21:08

1 Answer 1

1

A trick i often use is to organise it into a hash and let the string be the key. In this case, a hash of arrays, where each array is a list of the original elements in which the string can be found:

#!/usr/bin/perl
use warnings;
use strict;

sub compare;

my @array;
$array[0] = "ABCD ABDC ACBD ABBC";
$array[1] = "ACBD ABCD AAAD ADBC BBAC";
$array[2] = "ABCD CCDB BDCB CABC";

compare(@array);

sub compare(@)
{
        my %sorted;
        my $i = 0;
        foreach my $element (@_)
        {
                my @strings = split(/\s+/,$element);
                foreach my $string (@strings)   {       push(@{$sorted{$string}}, $i)   }
                $i++;
        }

        foreach my $string (keys(%sorted))
        {
#               print scalar(@{$sorted{$string}}) . "\n";
                if ( scalar(@{$sorted{$string}}) == scalar(@_) ) { print "$string present in all elements\n" }
                else { print "$string missing in some elements\n" }
        }

}

The above code prints:

ABBC missing in some elements
ABCD present in all elements
CCDB missing in some elements
ABDC missing in some elements
AAAD missing in some elements
BBAC missing in some elements
BDCB missing in some elements
ACBD missing in some elements
CABC missing in some elements
ADBC missing in some elements

If you want, you can use the other print-line in the sub to get a more detailed report.

Disclaimer: This code is not written to be elegant or efficient, but to get the job done in an easily readable way. Well, as far as a hash of arrays can be easily readable, that is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.