从给定列表中找到 Collat​​z 序列的最大值 [英] find the max of Collatz sequence from a giving list

查看:43
本文介绍了从给定列表中找到 Collat​​z 序列的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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) ))

推荐答案

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

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))).

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

Or, if you let ((head (car items)), then they are (car head) and (car (cdr head)).

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

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.

这篇关于从给定列表中找到 Collat​​z 序列的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆