Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

backtracking

Name: Anonymous 2009-06-26 14:12

hey. i'm trying to do a backtracking solution to the 8 queens puzzle. i don't know why it doesn't works. care to help?
#include <iostream>
using namespace std;
#define N 8
bool validatablero(bool (*tablero)[N], int x, int y) {
/*    for (int j=0; j<=N-1; j++) {
        for (int i=0; i<=N-1; i++) {
            if (tablero[i][j]==true) {
                if (x==i && y==j)
                    std::cout << "f";
                else
                    std::cout << "x";
            } else {
                if (x==i && y==j)
                    std::cout << "f";
                else
                    std::cout << "o";
            }
        }
        std::cout << endl;
    }
    cout << endl;*/
    for (int j=0; j<=N-1; j++) {
        for (int i=0; i<=N-1; i++) {
            if (tablero[i][j]==true && (x>7 || x<0 || y>7 || y<0 || x==i || y==j || x-i==y-j || x-i==-(y-j))) { //todos los casos en el que las reinas se podrían atacar
                return false;//si ocurre la función es falsa.
            }
        }
    }
    return true;
}   
void cuin(bool (*tablero)[N], int r, bool *t) {//pide un tablero, un contador para el número de reinas y un booleano para verificar que haya conseguido la solución
    for(int i=0; i<=N-1; i++) {
        for(int j=0; j<=N-1; j++) {//los ciclos me permiten hacer todos los movimientos posibles de las reinas
            if (validatablero(tablero, j, i)) {
                tablero[j][i]=true;//si validatablero es cierto, se puede poner la reina en esa posición
                if (r>=N) {//si el número de reinas que da r es igual al N, se consigue la solución
                    *t=true;
                    return;
                } else {//sino pasamos a la siguiente reina. aumentamos el contador en uno.
                    cuin(tablero, r++, t);
                    if (!*t)
                        tablero[j][i]=false; //si llegamos aqui y no hemos conseguido la solución, la reina no se cambia de posición
                }
            }
        }
    }
}
int main() {
    int x, y, z, w;
    bool f=false;
    bool tablero[N][N];
    for (int i=0; i<=N-1; i++) {
        for (int j=0; j<=N-1; j++) {
            tablero[i][j]=false;
        }
    }
    cuin(tablero, 1, &f);
    for (int j=0; j<=N-1; j++) { //imprimimos el tablero
        for (int i=0; i<=N-1; i++) {
            if (tablero[i][j]==true) {
                if (x==i && y==j)
                    std::cout << "f";
                else
                    std::cout << "x";
            } else {
                if (x==i && y==j)
                    std::cout << "f";
                else
                    std::cout << "o";
            }
        }
        std::cout << endl;
    }
}
thanks.

Name: Anonymous 2009-06-26 14:32

Please use the [code] tags.

Name: Anonymous 2009-06-26 14:32

HEY FUCKFACE, WANT MY FIST TO BACKTRACK PAST YOUR FACE?

Name: Anonymous 2009-06-26 14:44

Look at this expression and think again:

(x > 7 || x<0 || y>7 || y<0 || x==i || y==j || x-i==y-j || x-i==-(y-j))

Does it, by your definition make sense? Yes? Please, explain why.

Name: Anonymous 2009-06-26 14:49


if((x > 7 || x<0 || y>7 || y<0 || x==i || y==j || x-i==y-j || x-i==-(y-j)) {
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      if (tablero[i][j] == true)
        return false;
    }
  }
}

Name: Anonymous 2009-06-26 14:53

Shit. Now there's Mexicans in /prog/.

Name: Anonymous 2009-06-26 15:11

>>5
What

j and i aren't defined yet up there

Name: Anonymous 2009-06-26 15:41


getAtLoc board r c | r < 0 || c < 0         = 0
                   | r >= length board      = 0
                   | c >= length (board!!r) = 0
                   | otherwise              = board !! r !! c

-- checks if the top row to be placed above board is safe for a queen in column h
isSafe [] _          = True
isSafe board       h = all (==0) (map (!!h) board) &&
                       all (==0) (foldl (flip $ (:).getFromDiagnal (+)) [] [0..length (head board)-h-1]) &&
                       all (==0) (foldl (flip $ (:).getFromDiagnal (-)) [] [0..h-1])
                 where getFromDiagnal f q = getAtLoc board q $ f h (q+1)

insertAt ys j n = insertAt' ys 0
            where insertAt' [] q          = [j]
                  insertAt' xs q | q == n = j:xs
                  insertAt' (x:xs) q      = x:insertAt' xs (q + 1)

queens boardSize = queens' boardSize
               where queens' 1 = possibleBoards []
                     queens' s = newBoards
                             where boardsTilNow = queens' $ s - 1
                                   newBoards = boardsTilNow >>= possibleBoards
                     emptyList = replicate (boardSize - 1) 0
                     possibleBoards b = map (:b) $ possibleRows b
                     possibleRows b   = map (insertAt emptyList 1) $ possibleSpaces b
                     possibleSpaces b = filter (isSafe b) [0..boardSize - 1]


There are 92 possible solutions to the 8x8 queens puzzle.

Name: Anonymous 2009-06-26 15:51

I just line up all 8 queens in a row. The trick is, they're all the same colour, so by the rules they can't attack each other.
It's still a pretty expensive algorithm, though; you only get one queen of each colour in a chess set, so you'll have to buy eight sets.

Name: Anonymous 2009-06-26 15:54

fgsfds

Name: FrozenVoid 2009-06-26 16:14

Name: FrozenVoid 2009-06-26 16:27

#include <stdio.h>
//copied from wikipedia article on 8queens solutions
#define QUEENS 8 //change to number of queens
int b[QUEENS];
inline static int unsafe(int y){int i,t,x;x=b[y];for(i=1;i<=y;i++){t=b[y-i];if((t==x)||(t==x-i)||(t==x+i)){return 1;}};return 0;}
static void putboard(void){static int s=0;int x,y;printf("\n\nSolution #%i\n",++s);for(y=0;y<QUEENS;y++){
   for(x=0;x<QUEENS; x++){printf((b[y]==x)?"|Q":"|_");};printf("|\n");}}
int main(void){int y=0;b[0]=-1;while(y>=0){do{b[y]++;}while((b[y]<QUEENS)&&unsafe(y));
  if(b[y]<QUEENS){if(y<(QUEENS-1)){b[++y]=-1;}else{putboard();}}else{y--;}};return 0;}




__________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-26 17:26

>>9
You can make your own from wood.

Name: FrozenVoid 2009-06-26 17:40

>>13 Thats not the Linux way. You have to grow your own tree and then make wood.

______________________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-26 17:41

>>13
Wood doesn't grow on trees, you know.

Name: FrozenVoid 2009-06-26 17:44

>>15 It does. Its just requires a correct configuration and drivers to grow it. I assume you can setup your own driver.

________________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-26 17:55

>>2
sorry about that
>>3
shut the fuck up
>>4
(x > 7 || x<0 || y>7 || y<0 || x==i || y==j || x-i==y-j || x-i==-(y-j))
it will fail if x or y are bigger than 7 (the last row/column of the chessboard[although this shouldn't ever happen]), or it wouldn't be valid if x or y are in the same column/row where there's another queen, and i can't remember where did i get the other two from. i know it validates the diagonal queens.
but i'll check it. if you're pointing that, that's where the error should be.
>>5
what >>7 said
>>8
>>12
thanks bros, but i want to know what's wrong with my algorithm
>>11
so i can't just do it with my algorithm? is it impossible? if you'd be so kind, would you explain me why? this thing has been annoying me for days.

Name: Anonymous 2009-06-26 18:06

>>8
http://en.wikipedia.org/wiki/Eight_queens_puzzle_solutions
n_queens n width = foldl add_queen [[]] [1..n]
    where add_queen previous_solutions _ =
              [new_col : sol | sol <- previous_solutions,
                               new_col <- [1..width],
                               safe_queen new_col sol ]
          safe_queen new_col sol =
              all (\(col,row) -> col       /= new_col &&
                                 col + row /= new_col &&
                                 col - row /= new_col)
                  (zip sol [1..])

Name: 8 2009-06-26 18:29

>>18

*Main> length $ queens 10
724
(12.15 secs, 713552044 bytes)
*Main> length $ n_queens 10 10
724
(6.08 secs, 385197172 bytes)

I have failed you, /prog/

Name: Anonymous 2009-06-26 18:40

Maths my anus

Name: FrozenVoid 2009-06-27 1:39

>>19 713552044 bytes? even JavaScript doesn't eat that much RAM


______________________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-27 1:54

>>21
JavaScript can't solve that problem.

Name: Anonymous 2009-06-27 2:13

>>19
| ?- findall(Y,nqueens(10,X),Z),length(Z,N).

N = 724
Z = [_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_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,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_]

(87 ms) yes


/* Generates a list which represents a single solution
   with the specified length and ensures that the list has each value
   from 1 to N once and only once. */
nqueens(N,Ls) :- length(Ls,N),
               fd_domain(Ls,1,N),
               fd_all_different(Ls),
               constraint_queens(Ls),
               fd_labeling(Ls,[variable_method(random)]).

/* Ensures that all positions are valid */
constraint_queens([]).
constraint_queens([X|Xs]) :- noattack(X,Xs,1), constraint_queens(Xs).

/* Ensures that no queens share diagonals */
noattack(_,[],_).
noattack(X,[Y|Xs],N) :- X#\=Y+N, X#\=Y-N, T=N+1, noattack(X,Xs,T).

Name: FrozenVoid 2009-06-27 4:18

I've optimized the wiki code into this:
http://frozenvoid.blogspot.com/2009/06/8queens-puzzle-solver.html



______________________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-27 4:58

>>24
how does it compare to >>23?

Name: FrozenVoid 2009-06-27 5:23

>>25 Takes too long after queens>13
There probably better search methods, like constraints but they would be more verbose in C
The code in my blog is just several loops.

_______________________________________________
http://xs135.xs.to/xs135/09042/av922.jpg
orbis terrarum delenda est

Name: Anonymous 2009-06-27 13:10

>>25
Terrible!

Name: Anonymous 2009-06-27 16:58

all in all no one helped me |:

Name: Anonymous 2009-06-27 17:33

>>28
Should have used code tags.

Name: Anonymous 2009-06-27 21:43

>>28
>>23 did.

Don't change these.
Name: Email:
Entire Thread Thread List