我正试图为四骑士问题获得3x3棋盘。这是球拍语言中的代码
#lang racket
(define N 3)
(define nexts ; construct the graph
(let ([ds (for*/list ([x 2] [x* '(+1 -1)] [y* '(+1 -1)])
(cons (* x* (+ 1 x)) (* y* (- 2 x))))])
(for*/vector ([i N] [j N])
(filter values (for/list ([d ds])
(let ([i (+ i (car d))] [j (+ j (cdr d))])
(and (< -1 i N) (< -1 j N) (+ j (* N i)))))))))
(define (tour x y)
(define xy (+ x (* N y)))
(let loop ([seen (list xy)] [ns (vector-ref nexts xy)] [n (sub1 (* N N))])
(if (zero? n) (reverse seen)
(for/or ([next (sort (map (λ(n) (cons n (remq* seen (vector-ref nexts n)))) ns)
< #:key length #:cache-keys? #t)])
(loop (cons (car next) seen) (cdr next) (sub1 n))))))
(define (draw tour)
(define v (make-vector (* N N)))
(for ([n tour] [i (in-naturals 1)]) (vector-set! v n i))
(for ([i N])
(displayln (string-join (for/list ([j (in-range i (* N N) N)])
(~a (vector-ref v j) #:width 2 #:align 'right))
" "))))
(draw (tour (random N) (random N)))
它给了我这个错误for: expected a sequence for n, got something else: #f
并突出显示了我的代码的这一部分:
(define (draw tour)
(define v (make-vector (* N N)))
(for ([n tour] [i (in-naturals 1)]) (vector-set! v n i))
(for ([i N])
(displayln (string-join (for/list ([j (in-range i (* N N) N)])
(~a (vector-ref v j) #:width 2 #:align 'right))
" "))))
而且我不确定问题是什么。这是为了上课,我对球拍语言没有经验。任何帮助,将不胜感激。感谢
答案 0 :(得分:1)
错误声明它期望for子句n
迭代序列(列表,字符串,vecor,范围,惰性序列)而不是#f
,它是作为结果传递的没有解决方案的tour
程序。
tour
的结果是for/or
的结果,如果没有任何迭代以给定的起始位置结果,则#f
(false)。对于3x3
和4x4
,无论起始位置都没有解决方案,5x5
有解决方案,但并非适用于所有起始位置。例如。例如。如果您的随机数字选择(1,2)
,那么也没有解决方法。要修复此检查,如果找到解决方案,只有在有解决方案时进行绘制:
(let* ((x (random N)) (y (random N)) (result (tour x y)))
(if result
(draw result) ; only draw when result is not #f
(displayln (format "No results for initial position (~a,~a)" x y))))
我之前的观点是,for
没有采取数字是错误的。它会将其解释为range
并迭代[0,N>
。我假设的原因是for documentation无法找到此功能。
(for/list ([n 10]) n) ; ==> (0 2 3 4 5 6 7 8 9)