Ganda
Ganda

Reputation: 175

N-Queens Scheme: trying to print out chessboard

It is working fine and I've checked manually that everything is running, but I now need to figure out how to print out the answer in a chessboard like fashion, where I have an nxn board of 0's and 1's, where 1's are the queens. I am using vectors and for example lets say I run nq-bt for a 5x5 board I get the answer: #(0 2 4 1 3)

nq-bt is the method that gives me the answer above

Here is my pseudocode for trying to get this to work:

(define (print-answer n)
    (make n equal to the returned vector of method (nq-bt))
    (loop until it hits end of the returned vector_length)
       (set value equal to (vector ref of n (*variable used for first loop)))
       (loop again the length of returned vector_length)
           (print 0's until hits vector ref's value, then print 1, then print 0's till end of loop)
           (print newline)))))

I know this is insane pseudocode, but my problem is that I'm not used to scheme and there isn't too much documentation on how I could do any of this. Any help would be greatly appreciated.

Upvotes: 0

Views: 109

Answers (1)

Óscar López
Óscar López

Reputation: 236034

You didn't mention which Scheme interpreter you're using, so first I'll show you a generic solution that uses standard procedures. For starters, we must decide how are we going to loop over the vector (say, using named lets).

Also notice that I changed the input parameter, it's easier if we pass the board's solution, besides I don't see how you can use the size n of the board if nq-bt doesn't receive it as a parameter (I hope nq-bt isn't obtaining n from a global define, that wouldn't be right):

(define (print-answer board)
  (let outer-loop ((i 0))
    (cond ((< i (vector-length board))
           (let ((queen (vector-ref board i)))
             (let inner-loop ((j 0))
               (cond ((< j (vector-length board))
                      (display (if (= queen j) 1 0))
                      (display " ")
                      (inner-loop (+ j 1))))))
           (newline)
           (outer-loop (+ i 1))))))

Now, if you're lucky and use Racket we can write a simpler and more idiomatic implementation without all the kludge of the previous solution:

(define (print-answer board)
  (for ([i (in-range (vector-length board))])
    (let ([queen (vector-ref board i)])
      (for ([j (in-range (vector-length board))])
        (printf "~a " (if (= queen j) 1 0))))
    (newline)))

Either way we can call print-answer with the result returned by nq-bt. For example:

(print-answer '#(0 2 4 1 3))

1 0 0 0 0
0 0 1 0 0
0 0 0 0 1
0 1 0 0 0
0 0 0 1 0

Upvotes: 1

Related Questions