2013-10-30 34 views
0

以下代碼在計算多少個值小於或等於用戶輸入的值「z」時有任何錯誤嗎?特別是,我希望有人看看這段代碼的最終功能,告訴我是否有任何錯誤。「計算堆中的不等式」

(define (create-heap v H1 H2) 
(list v H1 H2)) 
(define (h-min H) (car H)) 
(define (left H) (cadr H)) 
(define (right H) (caddr H)) 

(define (insert-h x H) 
    (if (null? H) 
    (create-heap x '() '()) 
    (let ((child-value (max x (h-min H))) 
     (root-value (min x (h-min H)))) 
    (create-heap root-value 
        (right H) 
        (insert-h child-value (left H)))))) 

(define (insert-all lst H) 
    (if (null? lst) 
    H 
    (insert-all (cdr lst) (insert-h (car lst) H)))) 

(define (count-less-than-or-equal-in-heap z H) 
    (cond ((or (null? H) (> (h-min H) z)) 0) 
     (else 
     (+ 1 (count-less-than-or-equal-in-heap z (right H)) 
      (count-less-than-or-equal-in-heap z (left H)))) 
     )) 
+1

你可能對堆棧溢出不會得到很大的成績,如果你沒有一個規劃問題(或者至少,不知道你們是否做)。如果您懷疑這可行,那麼您可以在http://codereview.stackexchange.com/找到更好的運氣。 「關於您編寫​​的代碼問題的問題必須在問題本身中描述具體問題 - 幷包含有效代碼以再現問題。」 –

+0

好的,謝謝你的鏈接,我不知道那個網站。 –

回答

1

有沒有錯誤:

> (define heap (insert-all '(0 5 10 15) '())) 
> (count-less-than-or-equal-in-heap -1 heap) 
0 
> (count-less-than-or-equal-in-heap 0 heap) 
1 
> (count-less-than-or-equal-in-heap 15 heap) 
4 

> (set! heap (insert-all '(0 5 5 5) '())) 
> (count-less-than-or-equal-in-heap 0 heap) 
1 
> (count-less-than-or-equal-in-heap 5 heap) 
4 
> (count-less-than-or-equal-in-heap 50 heap) 
4 
+1

感謝您的幫助! –