#!/usr/bin/perl # # Matrix Spiral # use strict; use warnings; # # Size of input matrix in columns and rows # my $cols = 7; my $rows = 3; # # Decrement rows & columns because we're using them as array indices # (i.e. counting from 0 not 1) # $cols--; $rows--; # # Populate a list of elements to feed the matrix from # my @elements; while () { # # Display data to screen so we can compare results to it # print; push @elements, (split(' ', $_)); } # # Keep the size of elements for after we've shifted it empty # my $count = @elements; # # Populate a matrix of the elements # which pacman can then walk around & eat pill by pill... # my @matrix; for my $row (0 .. $rows ) { for my $col (0 .. $cols ) { $matrix[$col][$row] = shift(@elements); } } my @output; my $x = 0; # X position in matrix my $y = 0; # Y position in matrix my $v = 0; # Vertical direction my $h = 1; # Horizontal direction my $row_s = 0; # Current Row start my $row_e = $rows; # Current Row end my $col_s = 0; # Current Column start my $col_e = $cols; # Current Column end for my $place ( 0 .. $count-1 ) { # # Show X and Y coordinate in bounds "min reached last col. go v\n"; $h = 0; # Stop horizontal movement (was right) $v = 1; # Go down # Finished highest remaining row # so remove it from matrix bounds $row_s++; } elsif ( $h == 0 && $v == 1 && $x == $col_e && $y == $row_e ) { print "v reached last row. go <\n"; $h = -1; # Go left $v = 0; # Stop vertical movement (was down) # Finished rightmost remaining column # so remove it from matrix bounds $col_e--; } elsif ( $h == -1 && $v == 0 && $x == $col_s && $y == $row_e ) { print "< reached first col. go ^\n"; $h = 0; # Stop horizontal movement (was left) $v = -1; # Go up # Finished lowest remaining row # so remove it from matrix bounds $row_e--; } elsif ( $h == 0 && $v == -1 && $x == $col_s && $y == $row_s ) { print "^ reached first row. go >\n"; $h = 1; # Go right $v = 0; # Stop vertical movement (was up) # Finished leftmost remaining column # so remove it from matrix bounds $col_s++; } # # Increment (or decrement) matrix position pointer # $x += $h; $y += $v; } print join($/, @output), $/; __DATA__ a b c d e f g h i j k l m n o p q r s t u