Racket中的随机功能(更复杂)

时间:2022-04-17 22:01:54

I know the basics about random function in Racket but I am trying to do something more difficult.

我知道关于Racket中随机函数的基础知识,但我正在尝试做一些更困难的事情。

I am trying to develop a random function that gives randomly an element of a list I give to the function as parameter. For example:

我正在尝试开发一个随机函数,它随机给出一个列表元素,我给函数作为参数。例如:

‘(a h j l u) -> Output: h

‘(w t) -> Output: w

‘(l u t n) -> Output: t

Any help is welcome.

欢迎任何帮助。

2 个解决方案

#1


1  

Here's one option, assuming a non-empty list and using built-in procedures:

这是一个选项,假设一个非空列表并使用内置过程:

(define (pick-random lst)
  (first (shuffle lst)))

For example:

例如:

(pick-random '(1 2 3 4 5))
=> 3

#2


1  

A way would be to first get the length of the list, do (random len) to get a number [0,len-1] and use that with list-ref to get the element.

一种方法是首先得到列表的长度,做(随机len)得到一个数字[0,len-1]并使用它与list-ref来获取元素。

#1


1  

Here's one option, assuming a non-empty list and using built-in procedures:

这是一个选项,假设一个非空列表并使用内置过程:

(define (pick-random lst)
  (first (shuffle lst)))

For example:

例如:

(pick-random '(1 2 3 4 5))
=> 3

#2


1  

A way would be to first get the length of the list, do (random len) to get a number [0,len-1] and use that with list-ref to get the element.

一种方法是首先得到列表的长度,做(随机len)得到一个数字[0,len-1]并使用它与list-ref来获取元素。