![](/img/trans.png)
[英]How to optimize runtime on recursive Racket function to determine maximum of element in list?
[英]How to determine if a number is the largest element in a list - Using Racket
我正在嘗試為峰值編寫一個函數,該函數消耗列表以生成一個包含原始列表所有峰值的子列表。 前任。 (peaks (cons 1 (cons 6 (cons 4 (cons 5 empty))))) 應該產生 (cons 6 (cons 5 empty))
我的答案似乎是正確的,但我認為我在某處搞砸了,因為這不是正確的答案。 我使用遞歸做了一個輔助函數來確定列表中的最大數字,然后將其代入另一個遞歸函數以創建一個由最大數字組成的子列表。
關於我搞砸的地方有什么建議嗎? 我們剛剛開始學習遞歸,這是唯一讓我感到困惑的問題。
(cond
[(empty? (rest lon)) (first lon)]
[else (max (first lon) (greatest (rest lon)))]))
(define (peaks lon)
(cond
[(empty? (rest lon)) lon]
[(equal? (first lon) (greatest lon)) (cons (first lon) (peaks (rest lon)))]
[else (peaks (rest lon))]))```
一個可能的解決方案是:
(define (peaks lst)
(cond [(empty? lst) lst]
[(empty? (rest lst)) lst]
[(empty? (rest (rest lst))) (list (max (first lst) (second lst)))]
[(<= (first lst) (second lst)) (peaks (rest lst))]
[else (cons (first lst) (peaks (rest (rest lst))))]))
例子:
> (peaks '(1 6 4 5))
'(6 5)
> (peaks '(9 1 2 6 7 3 4 5 0 8))
'(9 7 5 8)
> (peaks '())
'()
> (peaks '(7))
'(7)
> (peaks '(7 3))
'(7)
> (peaks '(3 4))
'(4)
> (peaks '(5 0 8))
'(5 8)
> (peaks '(6 7 3))
'(7)
我可能會像這樣接近它。 首先,我編寫了一個函數is-peak
,它確定三 (3) 個相鄰元素是否在中間元素中包含一個峰值 -
(define (is-peak a b c)
(and (< a b) (> b c)))
然后我使用模式匹配為包含元素 0、1、2、3 或更多元素的列表編寫了一個peaks
程序 -
(define (peaks ls)
(match ls
;; 0, 1, or 2-element lists do not have peaks
[(list) null]
[(list a) null]
[(list a b) null]
;; 3-element lists could have at most 1 peak
[(list a b c)
(if (is-peak a b c)
(list b)
null)]
;; 4 elements or more
[(list a b c d ...)
(if (is-peak a b c)
(cons b (peaks (cddr ls)))
(peaks (cdr ls)))]))
(peaks (list 1 2 1 3 4 5 4 2 1 5 6 7 4))
'(2 5 7)
我們可以將線性過程可視化並跟蹤a
, b
, c
, d ...
。 請注意cddr
如何讓我們在找到峰值后快進一個元素。 這是因為一個峰永遠不可能與另一個峰相鄰——
一種 | 乙 | C | …… |
---|---|---|---|
1 | 2 (峰值) | 1 | 3 4 5 4 2 1 5 6 7 4 |
1 | 3 | 4 | 5 4 2 1 5 6 7 4 |
3 | 4 | 5 | 4 2 1 5 6 7 4 |
4 | 5 (峰值) | 4 | 2 1 5 6 7 4 |
4 | 2 | 1 | 5 6 7 4 |
2 | 1 | 5 | 6 7 4 |
1 | 5 | 6 | 7 4 |
5 | 6 | 7 | 4 |
6 | 7 (峰值) | 4 |
現在我們將考慮其他一些peaks
輸入 -
(peaks (list 1 2 3 2 1))
(peaks (list 3 2 1 2 3))
(peaks null)
'(3)
'()
'()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.