in reply to creating adjacency matrix

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"; } }

Replies are listed 'Best First'.
Re^2: creating adjacency matrix
by ramdat (Initiate) on Jan 11, 2011 at 04:51 UTC
    Thank you very much..It worked for me.Likewise i understood @square_matrix returns address values and But I am not able understand the squarebraces of @x use in the map function..Would be thankful to your answer..
      The matrix is represented as an array of arrays.
      Add a use Data::Dumper; statement, then various print Dumper \@square_matrix; statements to see how the data is being represented.
      example of a 3x3: my @m = ([0,0,0], [0,0,0], [0,0,0]);
      Each "row" is what the [@x] represents and is the return value of the map. Another set of code in this thread uses a hash table to represent the data.

      The main idea is to make a square matrix and then each set of letters results in two entries into that matrix. Many implementations of that idea are possible, some much shorter than what I did in this case.

      Update:

      This might help you to understand what is going on without a map...a map is kind of like a "tricky" foreach() loop.

      #!/usr/bin/perl -w use strict; use Data::Dumper; my @sq_matrix_3x3; my @list = (1,2,3); foreach (@list) { push (@sq_matrix_3x3, [0,0,0]); #creates a row with 3 elements } print "3x3 Matrix: "; print Dumper \@sq_matrix_3x3;
      This is the same thing and perhaps a more familiar form of [x][y] coordinates
      my @another_2D; for (my $x=0; $x<3; $x++) { for (my $y=0; $y<3; $y++) { $another_2D[$x][$y]=0; } } print Dumper \@another_2D; __END__ prints: 3x3: $VAR1 = [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]; # print Dumper \@sq_matrix_3x3; #these both produce the same output # print Dumper \@another_2D;