use Algorithm::Permute; 
use strict;
use warnings;

my $filename = shift;
my $n = shift;
our @r = @ARGV;
our @s = pSums(@r);
mainLoop($filename, $n);

sub mainLoop
{
	open(OUTPUT, ">>".shift);
	my $n = shift;
	print OUTPUT "Begin log: n=$n, r=(@r).\n";
	my @res;
	my $perm = new Algorithm::Permute([1..$n]);
	while (@res = $perm->next)
	{
		if (test(\@res)) { print OUTPUT "g=(@res) works for r=(@r)!\n"; }
	}
	print OUTPUT "End log.\n\n";
}

sub test
{
	my $input = shift;
	my %h;
	grep(((++$h{abs(@$input[$_]-@$input[$_+1])}==1) or (return 0)), (0..@$input-2));
	return 0 unless (abs(@$input[$s[0]]-@$input[0]) == abs(@$input[$s[0]+1]-@$input[$s[0]]));
	grep(((abs(@$input[$s[$_]]-@$input[$s[$_-1]+1]) == abs(@$input[$s[$_]+1]-@$input[$s[$_]])) or (return 0)), (1..@s-1));
	print "@$input works!\n";
	return 1
}

sub pSums
{
	my @s;
	my @input = @_;
	$s[0] = $input[0]-1;
	for (1..@input-1) { $s[$_] = $s[$_-1] + $input[$_]; }
	return @s;
}