RosettaCodeData/Task/N-queens-problem/Mathematica/n-queens-problem-3.math

9 lines
797 B
Plaintext

n=8;cnt=1;per=Permutations[Range[n],{n}];(* All Permutations of length n *)
Do[per[[q]]=Partition[Riffle[Reverse[Range[n]],per[[q]]],2],{q,1,Length[per]}];(* Riffled in the reverse of [range n] partitioned into pairs*)
Do[w=Subsets[per[[t]],{2}];(* This is a full subset of the previous set of pairs taken 2 at a time *)
tot=0;
Do[y=Abs[w[[q,1,1]]-w[[q,2,1]]];x=Abs[w[[q,1,2]]-w[[q,2,2]]];If[x==y,tot++],{q,1,Length[w]}];(* x and y are the abs values of x1-y1 and x2-y2 if equal they are on same diagonal *)
If[tot==0,g=Grid[Table[" ",{n},{n}],Alignment->Center,Frame->All,Spacings->{1.2,1}];(* If no clashing diagonals setup an array and print the permutation and the grid*)
Do[g[[1,per[[t,w,1]],per[[t,w,2]]]]="Q",{w,1,n}];
Print[cnt," ",per[[t]]," ",g];cnt++],{t,1,Length[per]}]