6
\$\begingroup\$

You've probably heard of the classic Eight Queens Puzzle. For those of you who haven't it goes something like this:

Position 8 queens on an 8×8 chessboard so that no two queens threaten each other (no two queens appear on the same row, column or diagonal as each other).

Here is one answer that is very close:

X - - - - - - -
- - - - X - - -
- X - - - - - -
- - - - - X - -
- - X - - - - -
- - - - - - X -
- - - X - - - -
- - - - - - - X

As you can see, two queens appear on the long diagonal between the top left corner and the bottom right corner.

Your task is to solve the Eight Queens Puzzle (using any programming language) in a unique or obfuscated manner. The first answer to 15 up-votes wins (the number may be subject to change depending on the popularity of this question).

Your output must be like the example above (empty squares represented by -, queens represented by X and a space between each X or -). Good luck!!

\$\endgroup\$
  • \$\begingroup\$ How much obfuscation is required? \$\endgroup\$ – jdstankosky Apr 12 '13 at 13:17
  • 2
    \$\begingroup\$ Can I use pre-solved results, or do I HAVE to solve this programmatically? Just wondering because I found a solution in my head pretty quickly. \$\endgroup\$ – jdstankosky Apr 12 '13 at 13:25
  • \$\begingroup\$ It's a popularity contest so, as much or as little as you like @jdstankosky \$\endgroup\$ – LazySloth13 Apr 12 '13 at 13:43
  • 5
    \$\begingroup\$ This is not very interesting, because there are 12 unique, known solutions. There is no variability at all, so just printing out a solution will always win. Why not generalize it, like: chess board size and number of queens are taken as input, and the program has to solve or say there is no solution? Also, why not give a good winning criterion? \$\endgroup\$ – user7486 Apr 12 '13 at 14:59
  • 2
    \$\begingroup\$ I'm voting to close this question as off-topic because there are only 12 possible outputs, and a correct solution just has to print one of them. There's no variation of inputs, and therefore none of outputs. \$\endgroup\$ – wizzwizz4 Feb 1 '16 at 8:10

10 Answers 10

6
\$\begingroup\$

Mathematica

The following implementation challenges the player to find one or more solutions to the eight queens problem. (It was too easy to simply have the program output the answers.)

Clicking on any of the squares in the chessboard toggles between "queen" and . When show attacks is checked, any attacks between queens are highlighted.

The following picture queenImg.

queen

In the board below, no queen attacks another:

queen1

Placing a fourth queen on a conflicting square results in two reciprocal attacks.

queen2

The following is one of the solutions.

solution

DynamicModule[{qns = ConstantArray[0, {8, 8}]}, 
Manipulate[
ClickPane[
Dynamic[ArrayPlot[
 Array[Boole[(Mod[#1, 2] == 0 \[And] 
       Mod[#2, 2] == 0) \[Or] (Mod[#1, 2] == 1 \[And] 
       Mod[#2, 2] == 1)] &, {w, w}], 
 ColorRules -> {1 -> White, 0 -> LightBrown}, Mesh -> True,
 Epilog -> {Red, Thickness[.005],
   If[attacks, 
    Line[Cases[
       Tally@Flatten[z[##] & /@ (Reverse /@ Position[qns, 1]), 
         1], {a_, n_} /; n > 1][[All, 1]]], {}], 
   Table[Inset[queenImg, p, Automatic, 10/w], {p, 
     Position[qns, 1] - .5}]}]], (qns = flip[qns, Ceiling@#]) &],
{{attacks, True, "show attacks"}, {True, False}},
Initialization -> (w = 8;
z[{r_, c_}] := {row[r], col[c], diag1[r, c], diag2[r, c]};   
row[r_] := {{0, r - .5}, {8, r - .5}};
col[c_] := {{c - .5, 0}, {c - .5, 8}};
diag1[r_, c_] := {{0, r - c}, {8 - (r - c), 8}};
diag2[r_, c_] := {{0, c + r - 1}, {c + r - 1, 0}};
flip[a_, pos_] := MapAt[(# - 1)^2 &, a, pos])]]
\$\endgroup\$
  • 1
    \$\begingroup\$ +1, nice program. Perhaps you could add some kind of feature to move the user-entered queens into an acceptable position. Then it would fulfill the challenge, too. \$\endgroup\$ – user7486 Apr 15 '13 at 7:50
4
\$\begingroup\$

dc

[sSdlS*]sw[d252-lwx26482+lwx1504824-lwx50051569+lwx982283196-lwx10821394332+lwx58071763728-lwx99637122816+]sa10 0:d0[laxd*453%;d1100.8*11552+P1+d8%;dPd64>s]dssx

Also at 160 characters it's decently short.

\$\endgroup\$
3
\$\begingroup\$

Ruby >=1.9

queens = %w[Anne-Marie Mary Elizabeth Victoria Maleficent Gertrude Alexandra Latifa]
SQUARES_ON_A_CHESSBOARD = 64

queens.permutation.find do |succession|
  i = SQUARES_ON_A_CHESSBOARD
  [-1,1].map{ |m| succession.map{ |queen| queens.index(queen) + m*i+=1}}.map(&:uniq).map(&:size).inject(&:*) == SQUARES_ON_A_CHESSBOARD
end.each do |queen|
  r=queens.map{queens[SQUARES_ON_A_CHESSBOARD & 1][SQUARES_ON_A_CHESSBOARD % 10]}
  r[queens.index(queen)]=(queens*SQUARES_ON_A_CHESSBOARD.to_s)[SQUARES_ON_A_CHESSBOARD]
  puts r.join(" ").upcase
end

Outputs one solution in the required format.

\$\endgroup\$
  • 2
    \$\begingroup\$ The queen names are a nice touch. :) \$\endgroup\$ – GalacticCowboy Apr 12 '13 at 19:49
2
\$\begingroup\$

Ruby

Q=8;$><<[*0...Q].permutation.select{|u|u.each_with_index.map{|a,b|[a-b,a+b]}.transpose.map{|z|z.uniq.size}==[Q,Q]}.map{|s|s.map{|f|(["-"]*(Q-1)+["X"]).rotate(f)*"\040"}*$/}*($/*2)

A not so much obfuscated but unique code - it contains function uniq ;-) but not a single whitespace! Prints all solutions to console. Maybe I'll start to obfuscate it somehow.

\$\endgroup\$
2
\$\begingroup\$

Haskell

import Data.List
import Control.Monad
import Control.Applicative

q8 = (sequence_ . (<$> (head.(foldM.flip.const) 
       (\_' -> join<$>sequence [(:[])<$>(((\_''-> [_''|
                 foldr (\(_''',_')->( (((==)<*>(\\[0,_''',-_''']))[_''-_']) &&)) 
                   (((/=)<*>((\\)>>=id)) [_']) $ zip [1..] _'])<$>[1..8])>>=id), 
                   [_'] ]) [] $ [1..8])))
       (\_' -> putStrLn$concat$replicate(_'-1)" -"++[" X"]++replicate(8-_')" -") 

Output:

 - - - X - - - -
 - X - - - - - -
 - - - - - - X -
 - - X - - - - -
 - - - - - X - -
 - - - - - - - X
 - - - - X - - -
 X - - - - - - -
\$\endgroup\$
2
\$\begingroup\$

Here is my solution in Python. This outputs every possible solution to the problem.

from itertools import permutations

def board(vector):
print ("\n".join('- ' * i + 'X ' + '- ' * (8-i-1) for i in vector) + "\n\n= = = = = = = =\n")


cols = range(8)
for vector in permutations(cols):
    if 8 == len(set(vector[i]+i for i in cols)) \
         == len(set(vector[i]-i for i in cols)):
        board (vector)

Here is a short sample of the output.

X - - - - - - - 
- - - - X - - - 
- - - - - - - X 
- - - - - X - - 
- - X - - - - - 
- - - - - - X - 
- X - - - - - - 
- - - X - - - - 

= = = = = = = =

X - - - - - - - 
- - - - - X - - 
- - - - - - - X 
- - X - - - - - 
- - - - - - X - 
- - - X - - - - 
- X - - - - - - 
- - - - X - - - 

= = = = = = = =

X - - - - - - - 
- - - - - - X - 
- - - X - - - - 
- - - - - X - - 
- - - - - - - X 
- X - - - - - - 
- - - - X - - - 
- - X - - - - - 
\$\endgroup\$
1
\$\begingroup\$

k

Relatively trivial solutions, For 32 characters:

-1'"-X"@0b\:'0x1002200140088004;

Slightly better (more painful to read than obfuscated):

((-).*:'(c;i))'@'[(*i)#,:(*i)#10h$45i;2/:'i#(*/(i:8 4))_0b\:*/c:7 129790099;:;10h$88i];
\$\endgroup\$
1
\$\begingroup\$

Q

Obfuscation through hideousness

nq:{
    f:{[]
        b:.[;;:;"X"]/[-1_'16 cut 128#"- ";flip (til 8;2*neg[8]?8)];
        v:{"X" in (x[;first where y="X"] each (til 8) except z)}[b]'[b;til 8];
        d:{"X" in x ./:{$[null r:1+last where raze (1#'x)=7;enlist -1 -1;x til r]}raze 1_{x,/:y}'[rotate[z;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
        e:{"X" in x ./:{$[null r:1+last where raze (1#'x)=0;enlist -1 -1;x til r]}raze 1_{x,/:y}'[reverse rotate[z+1;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
        (not any v,d,e;b)};
    while[not first q:f[];];
    -1 last q;
    }

.

q)nq[]
- - - X - - - -
- - - - - - - X
- - - - X - - -
- - X - - - - -
X - - - - - - -
- - - - - - X -
- X - - - - - -
- - - - - X - -
\$\endgroup\$
1
\$\begingroup\$

Python, Obfuscation through Complexity

Though you would see magic numbers in my code, they are not the hard-coded solution. On running the code, you would get the list of all possible positions of the queens

from itertools import*
from math import*
def foo():
    def bar(x):
        k1,k2,k4 = 6148914691236517205L,3689348814741910323L,1085102592571150095L
        x = ((x >> 1) & k1) | ((x & k1) << 1)
        x = ((x >> 2) & k2) | ((x & k2) << 2)
        x = ((x >> 4) & k4) | ((x & k4) << 4)
        return x
    op = [(9259542123273814144L,4,1,0),(9241421688590303745L,7,1,8),(9241421688590303745L,7,-1,-8)]
    for o in op:
        d=o[0]
        m=18446744073709551615L
        for n in range(o[1]):
            yield d
            yield bar(d)&18446744073709551615L
            m=(m<<o[3] if o[3]>0 else m>>-o[3])&18446744073709551615L
            d=(d>>o[2] if o[2]>0 else d<<-o[2])&(m)
for e in (int(''.join("{0:08b}".format(n) for n in p),2) for p in permutations((2**n for n in range(8)),8)):
    if all((round(log(m & e)/log(2),8)).is_integer() for m in foo() if m&e):
        print '\n'.join(''.join(e) for e in  zip(*[iter("{0:064b}".format(e))]*8))
        print '-'*8
\$\endgroup\$
  • 1
    \$\begingroup\$ You should make all your list comps into maps since that's always harder to read \$\endgroup\$ – jamylak Apr 13 '13 at 9:20
  • \$\begingroup\$ this is a wrong solution, since it prints positions in which queens attack themselves: 10000000 00100000 00001000 01000000 00010000 00000100 00000010 00000001 \$\endgroup\$ – Tudor Constantin Jan 28 '15 at 20:32
1
\$\begingroup\$

⍴Script (rhoScript)

You wanted obfuscated, well...

��ˠo����}���e���

Hexdump, for obvious reasons:

00000000: a991 cba0 6f87 c1fb e97d 82c1 cd65 e2f8  ....o....}...e..
00000010: 90 

In less-obfuscated form:

8 range permutations 
    (with-index 
        (sum) map uniq arg-a with-index 
                (*exploding subtract) map uniq concatenate length) 
keep-maxes-by

Yeah, I don't really know what it does either.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.