g | x | w | all
Bytes Lang Time Link
008APL Dyalog Extended171226T200107ZAdá
120Swift 6240308T183120ZmacOSist
029Uiua240309T180553Zjan
049J171226T215831Zmiles
122Befunge171226T015851ZJames Ho
044Charcoal171224T004047ZNeil
136Retina170724T212107ZNeil
145Haskell170724T191945Zბიმო
189Python 3170722T105707ZJames Ho
021Jelly170722T113646Zmiles
114C170721T193048Zorlp
222C170721T181939ZQuaerend
nanMathematica170721T151909ZKeyu Gan
3227MATL170721T145340ZLuis Men

APL (Dyalog Extended), 8 bytesSBCS

Anonymous tacit prefix function taking n as argument. Prints space-separated solution to stdout using · for empty squares and for Queens.

⊃⌂queens

Try it online!

⌂queens find all truly unique Queens' solutions (no reflections or rotations)

 pick the first solution


Original equivalent answer in vanilla APL (Dyalog Unicode), 18 bytesSBCS:

Full program prompting for n from stdin. Prints space-separated solution to stdout using · for empty squares and for Queens.

⎕CY'dfns'
⊃queens⎕

Try it online!

⎕CY'dfns'Copy the "dfns" library

 get input from stdin

queens find all truly unique Queens' solutions (no reflections or rotations)

 pick the first solution

Swift 6, 251 241 120 bytes

{let p=$0-$0%2,d=p/2,e=p%6<1 ?d:2
for y in 0..<$0{print({String.init}()(" ",y<p ?(p+y%d*2+(y<d ?e-1:2-e))%p:$0-1)+"Q")}}

Try it on SwiftFiddle!

Adapted from the C answer.

Uiua, 29 characters

≡(+@@=⇡)⧻.-1∵⟨⌈÷2-|-⌊÷2⟩◿2.⇡.

Apparently any grid output is enough:

≡(=⇡)⧻.∵⟨-1⌈÷2-|-⌈÷2⟩◿2.⇡.

Try it here!

J, 49 bytes

i.=/0({(1-.@e.,)@(([:(=#\){.|@-}.)\."1)#])!A.&i.]

Try it online!

Brute force by testing all permutations of length n.

Befunge, 122 bytes

&::2%-v>2*00g++00g%00g\-\00g\`*4>8#4*#<,#-:#1_$55+"Q",,:#v_@
/2p00:<^%g01\+*+1*!!%6g00-2g01\**!!%6g00-g012!:`\g01:::-1<p01

Try it online!

This is more or less based on the C solution by orlp.

Explanation

Source code with execution paths highlighted

* Read the number of queens, q, from stdin and calculate two variables for later use: n = q - q%2, and hn = n/2
* Start the main loop, iterating r, the row number, from q down to 0, decrementing at the start of the loop, so the first r is q minus 1.
* Calculate the offset of the queen in each row with the following formula:

offset = (n - (
  (hn <= r) * (2 - hn) * !!(n % 6) + 
  (hn > r) * ((hn - 2) * !!(n % 6) + 1) + 
  (y % hn * 2) + n
) % n) * (n > r)

* Output offset space characters to indent the queen's position for the current row, plus one additional space just because it makes the output loop easier.
* Output the Q for the queen, followed by a newline to move to the next row.
* Test if r is zero, in which case we've reached the end of the board and can exit, otherwise we repeat the main loop again.

Charcoal, 44 bytes

Nθ≔÷θ²ηEθ◧Q⊕⎇⁼ι⊗ηι⎇﹪η³﹪⁺⁺⊗ι⊖η׳¬‹ιη⊗η﹪⊕⊗ι⊕⊗η

Try it online! Link is to verbose version of code. Another port of @orlp's excellent C answer.

Retina, 136 bytes

.+
$* 
 
$_;$`Q¶
( +)\1( ?);
:$1;
:( +);\1\1
$1$1
:((   )+);( *)
 $1$1% $3$3
: ( +);( \1)?( *)
 $1 $1%$#2$* $#2$* $#2$* $1$3$3
( +)%\1?

Try it online! Port of @orlp's excellent C answer. Explanation:

.+
$* 

Convert to unary, using spaces (there is a space after the *).

$_;$`Q¶

Create N rows with N spaces, a ;, then 0..N-1 spaces, then a Q. The remaining stages apply to all rows.

( +)\1( ?);
:$1;

Integer divide N by 2. (Also wrap the result in :; to make it easier to anchor patterns.)

:( +);\1\1
$1$1

If the loop index equals N/2*2, then just leave that many spaces.

:((   )+);( *)
 $1$1% $3$3

If N/2 is a multiple of 3, then take double the loop index plus one, modulo N/2*2+1.

: ( +);( \1)?( *)
 $1 $1%$#2$* $#2$* $#2$* $1$3$3

Otherwise, take double the loop index plus (N/2-1) plus an extra 3 in the bottom half of the board, modulo N/2*2.

( +)%\1?

Actually perform the modulo operation.

Haskell, 145 bytes

The obvious brute force approach:

b=1>0
t[]=b
t(q:r)=all(/=q)r&&foldr(\(a,b)->(abs(q-b)/=a&&))b(zip[1..]r)&&t r
q n|y<-[1..n]=(\q->(' '<$[1..q])++"Q")<$>[x|x<-mapM(\_->y)y,t x]!!0

Try it online!

Python 3, 204 189 bytes

import itertools as p
n=int(input())
r=range(n)
b='.'*(n-1)+'Q'
for c in p.permutations(r):
 if len(set((x*z+c[x],z)for x in r for z in[1,-1]))==n+n:[print(*(b[x:]+b[:x]))for x in c];break

Brute force search through all permutations. I could remove the * and print the list comprehensions, but they look awful.

Output:

10
Q . . . . . . . . .
. . Q . . . . . . .
. . . . . Q . . . .
. . . . . . . Q . .
. . . . . . . . . Q
. . . . Q . . . . .
. . . . . . . . Q .
. Q . . . . . . . .
. . . Q . . . . . .
. . . . . . Q . . .

Slightly ungolfed:

import itertools as p
n=int(input())
r=range(n)
b='.'*(n-1)+'Q'
for c in p.permutations(r):
    if len(set( (x*z+c[x],z) for x in r for z in[1,-1] )) == n+n:
        [print(*(b[x:] + b[:x])) for x in c]
        break

Jelly, 24 21 bytes

,JŒc€IF€An/PC
ẊÇ¿=þRG

Try it online!

Assuming each queen are placed on separate rows, we only need to find the column indices to place each queen at to avoid conflicts, which can be found by generating a random permutation of [1, 2, ..., n] and testing it.

Explanation

,JŒc€IF€An/PC  Helper. Input: permutation of [1, 2, ..., n]
 J             Enumerate indices, obtains [1, 2, ..., n]
,              Join
  Œc€          Find all pairs in each
     I         Calculate the difference of each pair
      F€       Flatten each
        A      Absolute value
               (We now have the distance in column between each queen and
                the distance in rows between each queen. If they are unequal,
                the queens do not conflict with each other)
         n/    Reduce using not-equals
           P   Product, returns 1 only if they are all unequal
            C  Complement
               Returns 1 when there is a conflict, else 0

ẊÇ¿=þRG  Main.  Input: n
Ẋ        Shuffle (When given an integer, it will shuffle [1, 2, ..., n])
 Ç¿      While the helper returns 1, continue shuffling
     R   Range, gets [1, 2, ..., n]
   =þ    Equality table (Generates the board as a matrix)
      G  Pretty-print the matrix

C, 114 bytes

Q(n,o,y){o=n%2;n-=o;for(y=0;y<n+o;++y)printf("%*c\n",y<n?o+n-(n+y%(n/2)*2+(n%6?y<n/2?n/2-1:2-n/2:y<n/2))%n:0,81);}

Directly prints a solution in O(1) time.

C - 222 bytes

v,i,j,k,l,s,a[99];main(){for(scanf("%d",&s);*a-s;v=a[j*=v]-a[i],k=i<s,j+=(v=j<s&&(!k&&!!printf(2+"\n\n%c"-(!l<<!j)," #Q"[l^v?(l^j)&1:2])&&++l||a[i]<s&&v&&v-i+j&&v+i-j))&&!(l%=s),v||(i==j?a[i+=k]=0:++a[i])>=s*k&&++a[--i]);}

The code is not mine, but from the IOCCC. I hope I'm not breaking any rules. Also, this displays all solutions for N between 4 and 99. I'll try to get a TIO link later.

Mathematica, 103 108 110 117 bytes

-5 bytes for DuplicateFreeQ -> E!=##&@@@

-7 bytes for ReplacePart[Array[],] -> SparseArray[]

SparseArray[Thread@#&@@Select[Permutations@Range@#~Tuples~2,And@@(E!=##&@@@{#-#2,+##})&@@#&]->1,{#,#}]&

Return a 2D-array. It takes 2.76s to calculate f[6] and 135s for f[7]. (In the current version, - becomes 0 and Q to 1.

output

The algorithm is similar to MATL answer but here the code is completely brute-force.

MATL, 33 32 27 bytes

`x,GZ@]1Z?tt!P!,w&TXds]h1>a

Try it online!

Semi-brute force, non-determistic approach:

  1. Generate a random permutation of row positions
  2. Generate a random permutation of column positions
  3. Check that no queens share a diagonal or anti-diagonal
  4. Repeat if necessary.

The obtained solution is random. If you run the code again you may get a different valid configuration. Running time is also random, but the longest test case (n = 10) finishes in about 30 seconds in TIO most of the time.