Racket,在给定数量的列表中拆分列表

时间:2017-04-16 15:06:48

标签: racket

我想编写一个给出列表和数字的程序,在给定数量的列表中拆分列表。

例如,

(split 3 '(1 2 3 4 5 6 7 8 9 10))

应该制作三个列表(例如,因为列表是随机完成的):

‘(4 1 6)

‘(9 7 2)

‘(3 10 8 5)

它应该随机选择元素,这样创建的列表总是不同的。

一旦我有了代码,我会将它与我得到的in another question at this web进行比较。 (我正在学习球拍)

1 个答案:

答案 0 :(得分:0)

(define (n-way-split n lst)
  (define (go len* lst)
    (match len*
      ['() '()]
      [`(,len . ,len*-tail)
       (let-values ([(next-len-elems rest-of-elems) (split-at lst len)])
         (cons next-len-elems (go len*-tail rest-of-elems)))]))
  (go (n-way-split-length* n (length lst))
      (shuffle lst)))

(define (n-way-split-length* n len)
  (let*-values ([(quot rem)                     (quotient/remainder len n)]
                [(count/lists-of-length-quot)   (- n rem)]
                [(count/lists-of-length-quot+1) rem]
                [(size*) (append (make-list count/lists-of-length-quot   quot)
                                 (make-list count/lists-of-length-quot+1 (+ 1 quot)))])
    size*))