【问题标题】:find the max of Collatz sequence from a giving list从给定列表中找到 Collat​​z 序列的最大值
【发布时间】:2013-02-25 07:12:29
【问题描述】:

我是方案语法的新手。 这是我一直在做的项目的最后一部分。 我能够从给定的 Collat​​z 序列中找到最大值,但是项目的这一部分需要从多个 Collat​​z 序列列表中找到最大长度。 因此,例如给出这个列表:'((1 10)(10 200)(201 210)(900 1000),输出应该是这样的:'(20 125 89 174) 我需要找到数字 1 到 10 之间的最大长度,然后从 10 到 200 ets 这是我的代码:

#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.你还没有告诉我们“Collat​​z”序列是什么意思。这是一些技术术语吗? 2. 你的函数没有契约,所以很难判断像max-in-list 这样的函数是否格式良好。 (例如,它需要处理空列表吗?)。但是当然, 3. 你还没有写任何数据定义,所以很难说你的程序打算对哪些数据类进行操作。 (数字列表?数字元组列表?)我猜,在编写许多合约之前,您需要编写这些数据定义。

标签: scheme sequence collatz


【解决方案1】:

您传递给max-length-list 的列表中的每个项目都是一个包含两个数字和一个nil 的列表,例如(cons 1 (cons 2 '())).
第一个数字是(car (car items))
第二个是(car (cdr (car items)))

或者,如果您是let ((head (car items)),那么它们是(car head)(car (cdr head))

递归调用是微不足道的;你已经用find-max 处理了第一个元素,现在你只需要处理其余的元素。你显然已经知道如何做到这一点,因为你已经做到了。

【讨论】:

  • 谢谢你,我对第二个元素感到困惑,这个(汽车(cdr(汽车物品)))做了魔法
猜你喜欢
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多