Racket,将一个列表分成两个不同大小的列表.并且随机 [英] Racket, split a list in two different size lists. And randomly

查看:26
本文介绍了Racket,将一个列表分成两个不同大小的列表.并且随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,给出一个列表和一个百分比,将列表分成两个不同大小的列表.它应该随机选择元素,这样创建的列表总是不同的.这些代码能够做到这一点:

I would like to code a program that given a list and a percentage, splits the list in two different size lists. It should have random pick of the elements, that way the created lists are always different. These code is able to do that:

(define (clamp x a b)
  (max (min x b) a))

(define (split pct xs)
  (define pos (exact-round (* (clamp pct 0.0 1.0) (length xs))))
  (split-at (shuffle xs) pos))

这是一个例子:

(拆分 0.25 '(1 2 3 4 5 6 7 8 9))

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

'(6 2)

'(3 7 1 4 5 8 9)

'(3 7 1 4 5 8 9)

但是,我想用这个函数来实现相同的目的,而不是shuffle":

But, instead of "shuffle" I would like to use this function to achieve the same:

(define (get-randomly-no-pair list)
  (list-ref list (random (length list))))

因此,get-randomly-no-pair 从初始列表中随机获取一个元素.并且所有元素都用于创建两个列表.

so, get-randomly-no-pair takes one element randomly from the initial list. And all the elements are used to create both lists.

推荐答案

(define (shuffle-list lst)
  (define indexes (shuffle (range (length lst))))
  (lambda ()
    (begin0
      (list-ref lst (car indexes))
      (set! indexes (cdr indexes)))))

(define gen (shuffle-list (list 10 12 14 16 18 20))
(gen) ; ==> 14 (e.g.)

现在我看到你假设你需要传递列表然后我宁愿做一个映射器:

Now I see you assume you need to pass the list then I would rather make a mapper:

(define (shuffle-accessor len)
  (define indexes (list->vector (shuffle (range len))))
  (lambda (lst index)
    (list-ref lst (vector-ref indexes index))))

(define lst3-ref (shuffle-accessor 3))
(lst3-ref '(1 2 3) 0) ; ==> 3 (e.g.)
(lst3-ref '(6 7 8) 0) ; ==> 8

这篇关于Racket,将一个列表分成两个不同大小的列表.并且随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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