问题
i'm new in scheme syntax. this is the last part of the project i've been working on. i was able to find the max from a giving Collatz sequence, but this part of the project requires finding the max length from a multiple Collatz sequences lists. So for example giving this list : '((1 10) (10 200) (201 210) (900 1000) and the output should be like this : ‘(20 125 89 174) i need to find the maximum length between the number 1 to 10 and then from 10 to 200 ets here is my code :
#lang racket
; Part I
(define (sequence n)
(cond [(= n 1)
(list n)]
[(even? n)
( cons n(sequence( / n 2)))]
[(odd? n)
( cons n(sequence (+(* n 3) 1))) ] ))
(sequence 10)
; Part II
(define (find-length items)
(if (null? items)
(list )
(cons
(length (sequence(car items)))
(find-length (rest items))))
)
(find-length (list 10 16 22 90 123 169))
;Part III
(define max-in-list (lambda (ls)
(let ( (head (car ls)) (tail (cdr ls)))
(if (null? tail)
; list contains only one item, return it
head
; else find largest item in tail
(let ((max-in-tail (max-in-list tail)))
; return the larger of 'head' and 'max-in-tail'
(if (> head max-in-tail)
head
max-in-tail
)
)
)
)
))
(define (find-max i j)
( if (= i j)
(list)
(cons
(max-in-list (find-length(sequence i)))
(find-max (+ 1 i ) j)
))
)
(max-in-list(find-max 1 10))
(define (max-length-list items )
(if (null? items)
(list)
(cons
(find-max ? ?) ) ; how i can call this function ?
(max-length-list (?) ) ; how i can call this function ?
)))
(max-length-list '((1 10) (10 200) (201 210) (900 1000) ))
回答1:
Each item in the list you pass to max-length-list
is a list with two numbers and a nil
, e.g. (cons 1 (cons 2 '()))
.
The first number is (car (car items))
.
The second is (car (cdr (car items)))
.
Or, if you let ((head (car items))
, then they are (car head)
and (car (cdr head))
.
The recursive call is trivial; you've processed the first element with find-max
, now you just need to process the rest of them. You obviously already know how to accomplish that, since you've done it.
来源:https://stackoverflow.com/questions/15061809/find-the-max-of-collatz-sequence-from-a-giving-list