【问题标题】:Racket, split a list in two different size lists球拍,将列表拆分为两个不同大小的列表
【发布时间】:2017-04-14 00:38:20
【问题描述】:

这段代码将一个列表分成两个大小相等的列表:

(define (split ls)
  (if (or (null? ls) (null? (cdr ls)))
      (list ls '())
      (let ((next (split (cddr ls))))
        (list (cons (car ls) (car next))
              (cons (cadr ls) (cadr next))))))

我想构建一个代码(define (split size ls)),其中 size 有一个值,例如:0.20、0.50、0.63,它将进入第一个列表的数字(以 % 为单位)。

【问题讨论】:

  • split 中那样以确定的交替顺序进行拆分是否重要?无法准确实现时,函数如何对数字进行四舍五入有什么要求吗?
  • 不,当不能精确地达到时,如何四舍五入并不重要。现在我有了保持顺序的拆分示例,我想要另一个示例是元素随机发送到每个列表。所以得到的两个列表总是不同的。

标签: racket


【解决方案1】:

这是一种方法。

可以使用您的函数split,而不是使用辅助函数split-at

#lang racket

; clamp : number number -> number
;   make sure x is in the interval [a;b],
;   if not return a or b.
(define (clamp x a b)
  (max (min x b) a))


; split-list : number list -> list list
;   return two values:
;     - appending the two lists will produce the a list equal to the input list xs
(define (split-list pct xs)
  ; find the position to split the list
  (define pos (exact-round (* (clamp pct 0.0 1.0) (length xs))))
  ; split it
  (split-at xs pos))

(split-list 0.00 '(a b c d))
(split-list 0.25 '(a b c d))
(split-list 0.50 '(a b c d))
(split-list 0.75 '(a b c d))
(split-list 1.00 '(a b c d))

【讨论】:

  • 感谢您的代码。现在我有了保持顺序的拆分示例,我想要另一个示例是元素随机发送到每个列表。所以得到的两个列表总是不同的。请问,你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 2022-12-21
  • 2010-10-19
  • 1970-01-01
  • 2020-05-05
相关资源
最近更新 更多