This code "solves" artist's puzzle posted in Matrix Formation. The problem presented was to find the largest divisor for an N x N matrix of digits such that the numbers formed by joining the digits in each row and numbers formed by joining the digits in each column all have a common divisor. In addition, the following restrictions were added:  No formednumber should start with 0.
 No two formednumbers are allowed to be the same.
For example, a 2 x 2 matrix is solved as:
2 1
8 4
The numbers formed are: 21, 84, 28, and 14 which all have a divisor of 7.
The code below has come up with the follwing solutions:  2x2: Divisor 7, Rows 21, 84
 3x3: Divisor 44, Rows 132, 792, 660
 4x4: Divisor 416, Rows 2496, 9152, 1664, 2080
#!/usr/bin/perl
#
# NOTES: This code will not solve a 1 x 1 matrix as all numbers are "r
+eused"
#
use strict;
use warnings;
use constant TRUE => 1;
use constant FALSE => 0;
use constant MATRIX_DIM => 3; # Set your matrix size here
use constant MAX_NUM => (10 ** MATRIX_DIM)  1;
use constant DEBUG => 0; # 0=Nothing, 1=Summary, 2=Detail
use constant SEPARATOR => '';
# Since you need to find 2 times the matrix width distinct numbers, yo
+u cannot
# have a divisor greater than the maximum number divided by that produ
+ct.
#
# For example, a 3 x 3 matrix has a maximum number of 999. You need 6
+distinct
# numbers to "solve" the matrix, so the maximum possible divisor would
+ be 166.
# 166 would result in 166, 332, 498, 664, 830, and 996.
#
my $Divisor = int(MAX_NUM / (MATRIX_DIM * 2));
my @Num;
my @PermPtrs; # Saves the position of the pointers between GetNextPerm
+() calls
my @Sol=();
# GetNextPerm generates purmutations from the passed array (one at a t
+ime)
# and uses a global array of pointers (@PermPtrs). This method seems t
+o be
# fast and uses less memory than computing all the permutations at onc
+e.
#
# NOTE: The first time this sub is called, @PermPtrs should be an empt
+y array.
#
sub GetNextPerm
{
my $pNum=shift;
my $Perm='';
my @PtrStack;
if ($#PermPtrs > 1)
{
my $Ptr=MATRIX_DIM1;
while (TRUE)
{
$PermPtrs[$Ptr]++;
if ($PermPtrs[$Ptr] > $#$pNum)
{
push @PtrStack,$Ptr;
$Ptr;
return undef if ($Ptr == 1);
next;
}
else
{
my $OkInc=TRUE;
foreach (0..MATRIX_DIM1)
{
next if ($_ == $Ptr);
$OkInc=FALSE if ($PermPtrs[$_] == $PermPtrs[$Ptr]);
}
next unless($OkInc)
}
last unless ($#PtrStack > 1);
$Ptr=pop(@PtrStack);
$PermPtrs[$Ptr]=1;
}
}
else
{
@PermPtrs=(0..MATRIX_DIM1);
}
foreach (@PermPtrs)
{
$Perm.=SEPARATOR if (length($Perm));
$Perm.=$$pNum[$_];
}
return $Perm;
}
sub CheckSolution
{
my $pNum=shift;
my $CheckNum;
my $PossSol;
my $Ptr;
my @Sol=();
my %Check;
my %Num;
#
# This code checks every permutation of possible numbers (from the p
+assed
# numberarray) as rows and checks if there are MATRIX_DIM other numb
+ers
# (also in the passed array) which can act as columns.
#
# For example, with a 3 x 3 matrix, this code should go through each
+
# permutation of three number (for rows) from the passed array and s
+ee if
# there are three other numbers which would work with the selected r
+ows as
# their columns.
#
# WISH LIST: Verify members of each permutation for "fitness" in the
+ir
# assigned spot. "Fitness" means you do not put a number
+in the
# top row whose first digit is not the first digit of at
+least
# one other number... whose second digit is not the first
+ digit
# of at least one other number... etc... This may speed u
+p this
# section of the code.
#
# Benchmark the code which checks the columns (foreach $P
+tr block)
# That code gets executed a lot, and *may* benefit from r
+ecoding.
#
@PermPtrs=();
while($PossSol=GetNextPerm($pNum))
{
print "\t",'Checking ',$PossSol,'... ' if (DEBUG >= 2);
%Num=map { $_ => TRUE } @$pNum;
@Sol=split(SEPARATOR,$PossSol);
delete $Num{$_} foreach (@Sol);
foreach $Ptr (0..length($Sol[0])1)
{
$CheckNum='';
$CheckNum.=substr($_,$Ptr,1) foreach (@Sol);
if (defined($Num{$CheckNum}))
{
delete $Num{$CheckNum};
}
else
{
print 'nope',"\n" if (DEBUG >= 2);
@Sol=();
last;
}
}
last if ($#Sol > 1);
}
return @Sol;
}
while ($Divisor >= 1)
{
@Num=();
foreach (1..int(MAX_NUM / $Divisor))
{
next if (($Divisor * $_) < (MAX_NUM / 10)); # Numbers which begin
+with zero
push @Num, ($Divisor * $_);
}
print 'Checking solution for divisor ',$Divisor,': ',join('',@Num),
+"\n"
if (DEBUG >= 1);
@Sol=CheckSolution(\@Num);
last if ($#Sol > 1);
$Divisor;
}
print "\n";
if ($#Sol > 1)
{
print 'Maximum divisor is ',$Divisor,', solution is ',join('',@Sol)
+,"\n";
}
else
{
print 'No solution found...',"\n";
}
# End of Script
Observation: Unless I really missed something, I could not find a good CPAN module which would generate permutations of n distinct numbers taken r at a time. This problem led to the GetNextPerm() sub which uses a series or r pointers which are moved through the array of numbers generating one permutation at a time.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:

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.

