#!/usr/athena/bin/perl

$total = 3;			# the expected total for every row/col

$width = 2;			# number of cols
$height = 2;			# number of rows

@numbers = (0, 1, 2, 3);
				# the numbers that will be assigned to the boxes


@matrix = [];

recurse(0, 0, @numbers);

sub recurse {
    local ($x, $y, @left) = @_;
    local ($a, $b, @baz, $newx, $newy);
    
    if ($#left < 0) {
	if (check()){
	    print_matrix();
	}
    }
    else {
	for ($a = 0; $a <= $#left; $a++){
	    @baz = @left;
	    $matrix[$x][$y] = splice(@baz, $a, 1);
	    $newx = $x + 1;
	    if ($newx == $width){
		$newy = $y + 1;
		$newx = 0;
		if (!check_line($y)){
		    return;
		}
	    }
	    else{
		$newy = $y;
	    }
	    recurse ($newx, $newy, @baz);
	}
    }
}


sub check_line {
    local ($y) = @_;
    local ($x, $sum);
    $sum = 0;
    return 1;
    for ($x = 0; $x < $width; $x++){
	$sum += $matrix[$x][$y];
    }
    if ($sum != $total){
	return 0;
    }
    return 1;
}

sub check {
    local ($x, $y, $sum);
    print_matrix();
    for ($x = 0; $x < $width; $x++){
	$sum = 0;
	for ($y = 0; $y < $height; $y++){
	    $sum += $matrix[$x][$y];
	}
	if ($sum != $total){
	    return 0;
	}
    }
    return 1;
}


sub print_matrix {
    local ($x, $y, $sum);
    print "\n    ---------  \n";
    for ($x = 0; $x < $width; $x++){
	$sum = 0;
	for ($y = 0; $y < $height; $y++){
	    printf "%3d ", $matrix[$x][$y];
	    $sum += $matrix[$x][$y];
	}
	print "       =  $sum\n";
    }
}
