You are asking for basically an "and" table. There are a bunch of ways that this could be made faster. But this is a fairly straight-forward general solution that does what you asked for.
I did test this expanding to A-E and testing "C E" as a pair.
that printed:
A B C D E
A 0 1 0 0 0
B 1 0 1 0 0
C 0 1 0 1 1
D 0 0 1 0 0
E 0 0 1 0 0
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
=this prints
A B C D
A 0 1 0 0
B 1 0 1 0
C 0 1 0 1
D 0 0 1 0
=cut
my @vars = qw(A B C D);
my @square_matrix = map{ my @x;
push (@x,0) foreach @vars;
[@x]
}@vars;
my $num =0;
my %ltr2num = map{ $_ => $num++ }@vars;
my @pairs = ("A B", "B C", "C D"); ### the user input ####
foreach my $pair (@pairs)
{
my ($x, $y) = split ' ',$pair;
enter_pair_in_matrix ( $ltr2num{$x},
$ltr2num{$y},
\@square_matrix
);
}
dump_square_matrix(\@vars,\@square_matrix);
sub enter_pair_in_matrix
{
my ($x,$y,$ref_matrix) = @_;
$ref_matrix->[$x][$y]= 1;
$ref_matrix->[$y][$x]= 1;
}
sub dump_square_matrix
{
my ($ref_vars, $ref_matrix) = @_;
my @vars = @$ref_vars;
print " ","@vars\n";
foreach (@$ref_matrix)
{
print shift @vars, " @$_\n";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.