Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,37 +1,78 @@
# Quick and dirty solution, checking all permutations without backtracking (thus it's slow)
IsSafe := function(a)
local n, i, j;
n := Length(a);
for i in [1 .. n - 1] do
for j in [i + 1 .. n] do
if AbsInt(a[j] - a[i]) = j - i then
return false;
NrQueens := function(n)
local a, up, down, m, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
m := 0;
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
m := m + 1;
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
od;
return true;
end;
sub(1);
return m;
end;
Queens := function(n)
local p, a, v;
local a, up, down, v, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
v := [];
for p in SymmetricGroup(n) do
a := List([1 .. n], i -> i^p);
if IsSafe(a) then
Add(v, a);
fi;
od;
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
Add(v, ShallowCopy(a));
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
end;
sub(1);
return v;
end;
v := Queens(8);;
Length(v);
PrintArray(PermutationMat(PermListList([1 .. 8], v[1]), 8));
[ [ 0, 0, 1, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
NrQueens(8);
a := Queens(8);;
PrintArray(PermutationMat(PermList(a[1]), 8));
[ [ 1, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 1, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 1, 0 ],
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 0, 0, 0, 0 ] ]