no title added by anonymous on Thu Oct 19 22:16:23 2023

(import srfi-13
        srfi-28)

;;             0    1    2    3    4    5    6    7    8    9
(define +krn+ "NNRKRNRNKRNRKNRNRKRNRNNKRRNKNRRNKRNRKNNRRKNRNRKRNN")

(define (nth-empty str n)
  (define (inner str count idx)
    (let ((new-idx (+ 1 idx)))
      (if (> count 0)
          (if (< idx (string-length str))
              (if (char=? #\space (string-ref str idx))
                  (inner str (- count 1) new-idx)
                  (inner str    count    new-idx))
              '())
          new-idx)))

  (inner str n 0))

(define (chess960 id)
  (let* ((rank "        ")
         (q1 (quotient id 4))
         (r1 (remainder id 4))
         (q2 (quotient q1 4))
         (r2 (remainder q1 4))
         (q3 (quotient q2 6))
         (r3 (remainder q2 6)))
    (string-set! rank (+ 1 (* 2 r1)) #\B) ; light-square
    (string-set! rank (* 2 r2) #\B) ; dark-square
    (string-set! rank (nth-empty rank r3) #\Q)
    (let* ((start (* 5 q3))
           (krn (string->list (substring +krn+ start (+ start 5)))))
      (map (lambda (x)
             (string-set! rank (string-index rank #\space) x))
           krn))
    (display rank)))

(chess960 518)