检查节点的子集中是否存在单词

时间:2015-04-22 05:46:42

标签: scheme racket

我正在尝试创建一个函数,它接受一个字,一个电路板和两个电路板索引:一个行索引和一个列索引,如果该字存在于行ri,列ci和跟踪的板上,则返回true只从位置ri,ci向左或向上移动的路径(就像图中的x,y一样)。

 0 1 2 3 4 5 6 7 8 
0 . . . . . . . . . 
1 . . . . . . . . .
2 . . . . . . . . .
3 . . . . . . . . .
4 . . . . . . . . .
5 . . . . . . . . .
6 . . . . . . . . .

#|
   A Board is one of:
   – empty
   – (cons [ListOf X] Board) -board-cols items long 

   [ListOf X] is board-rows items long

   board? : X -> Bool
   make-board :  Nat Nat X -> Board
|# 
(define-struct board [rows cols content])

如果需要,这应该在ISL +中只有一个帮助器,但是没有其他本地,helper,lambdas,let等等,并且应该是二叉树递归。

我相信我已经非常接近解决这个问题了,但我仍然只有一些支票预期通行证。这就是我所做的:

 ;returns a character at the location
 ;this function doesn't count as a helper
    (define (board-ref b row col)
      (if (or (< (board-rows b) row) (< (board-cols b) col)) false
          (string-ref (list-ref (board-content b) row) col)))    

    ; find? : String Board Row Col -> Bool
        (define (find? w b ri ci)
          (local [(define (help w b ri ci n)
                    (cond 
                      [(= n (sub1 (string-length w))) true]
                      [else 
           (and (equal? (string-ref w n) (board-ref b ri ci))
                (or (equal? (string-ref w n) (help w b (sub1 ri) ci (add1 n)))  
                    (equal? (string-ref w n) (help w b ri (sub1 ci) (add1 n)))))]))] 
        (help w b ri ci 0)))

检查:

(define b0 (make-board 1 1 (list "x")))
(define b1 (make-board 5 5 
                       (list "reuta" "trmfk" "holte" "nsicd" "cexly")))
(define b2 (make-board 3 7 (list "jkialmw" "ienloer" "syilzbt")))
#;(check-expect (find? "x" b0 0 0) true)
#;(check-expect (find? "sort" b1 3 1) true)
#;(check-expect (find? "aikj" b2 0 3) true)
#;(check-expect (find? "aikji" b2 0 3) false)

任何帮助都会有很长的路要走。

1 个答案:

答案 0 :(得分:0)

你看起来有三个问题:

 [(= n (sub1 (string-length w))) true]

如果您尝试运行(find? "q" b0 0 0)会怎样?那显然应该失败,但事实并非如此。你过早地宣布匹配一个角色。 (这意味着可以在任何地方找到单个字符串。)只需考虑一个字符的情况; (string-length "q")为0.您可以通过将help调用n作为0来启动递归。

 (or (equal? (string-ref w n) (board-ref b ri ci))
     (help w b (sub1 ri) ci (add1 n))    
     (help w b ri (sub1 ci) (add1 n)))]))] 

考虑一下如何向某人解释该代码。它会像&#34;返回true,如果当前字符匹配,或者递归调用超过,或者向左递归调用成功。&#34;

您需要在每次通话时匹配当前字符((string-ref w n))。 or与两个递归调用一起发挥作用;你不关心哪一个成功,你只需要其中一个。

  (if (or (< (board-rows b) row)
          (< (board-cols b) col))
      false
      (string-ref (list-ref (board-content b) row) col)))    

当您触及顶部或左侧边缘时会发生什么情况,并且您仍然收到了您正在寻找的字母? rowcol将变为否定,然后list-refstring-ref不会感到高兴。在你对soegaard的评论中,你说递归应该上升,直到你达到0,0。但究竟是什么阻止了你呢?

相关问题