Question

I know this seems so trivial, but having only ever worked in declarative/imperative languages, I find myself having issues with this problem.

I have a checker-board (essentially an 8x8 list/array of states), and I need to be able to grab the (x y)th element of the board.

I figure given rest-of-board as board, if I can (rest rest-of-board) y-1 times, then return (first rest-of-board), I will have the row. Then if I (rest row) x-1 times, then return (first row), I will have the right element. Then I return with (result )?

     #lang scheme
     (define new-board '((P2 OFF P2 OFF P2 OFF P2 OFF)
                (OFF P2 OFF P2 OFF P2 OFF P2)
                (P2 OFF P2 OFF P2 OFF P2 OFF)
                (OFF BLANK OFF BLANK OFF BLANK OFF BLANK)
                (BLANK OFF BLANK OFF BLANK OFF BLANK OFF)
                (OFF P1 OFF P1 OFF P1 OFF P1)
                (P1 OFF P1 OFF P1 OFF P1 OFF)
                (OFF P1 OFF P1 OFF P1 OFF P1)))
     (define (get-state board x y))
Was it helpful?

Solution 2

Maybe a vector of vectors would be a better representation here:

(define new-board 
  (list->vector 
   (map list->vector 
        '((P2 OFF P2 OFF P2 OFF P2 OFF)
          (OFF P2 OFF P2 OFF P2 OFF P2)
          (P2 OFF P2 OFF P2 OFF P2 OFF)
          (OFF BLANK OFF BLANK OFF BLANK OFF BLANK)
          (BLANK OFF BLANK OFF BLANK OFF BLANK OFF)
          (OFF P1 OFF P1 OFF P1 OFF P1)
          (P1 OFF P1 OFF P1 OFF P1 OFF)
          (OFF P1 OFF P1 OFF P1 OFF P1)))))

(define (get-state board x y)
  (vector-ref (vector-ref board x) y))

(define (set-state! board x y val)
  (vector-set! (vector-ref board x) y val))

then

> (get-state new-board 0 1)
OFF
> (get-state new-board 1 1)
P2

> (set-state! new-board 1 1 'hi)
> (get-state new-board 1 1)
'hi

OTHER TIPS

Create an abstraction for this:

(define (make-board)
  (make-vector 64 'blank))

(define (board-ref board x y)
  (vector-ref board (+ (* y 8) x)))

(define (board-set! board x y new)
  (vector-set! board (+ (* y 8) x) new))

Go from there.

(define (board-fill board list-of-64-values) ...)    ;; for example
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top