Random 方案:结合随机和子串
我试图创建一个过程,让用户输入一个非空字符串,然后从长度为1的子字符串中的输入返回一个随机字母 i、 e 到目前为止,我已经:Random 方案:结合随机和子串,random,scheme,substring,Random,Scheme,Substring,我试图创建一个过程,让用户输入一个非空字符串,然后从长度为1的子字符串中的输入返回一个随机字母 i、 e 到目前为止,我已经: (define pick-at-random (lambda (s) (substring s (random(string-length s)) ()))) 这给了我想要显示的字母的位置,我觉得()在哪里,我应该有一些表示子字符串起始值的变量,然后向其中添加一个。然而,我不知道该怎么做。简单地说,我在问如何在使用起始值中的随机函数
(define pick-at-random
(lambda (s)
(substring s (random(string-length s)) ())))
这给了我想要显示的字母的位置,我觉得()在哪里,我应该有一些表示子字符串起始值的变量,然后向其中添加一个。然而,我不知道该怎么做。简单地说,我在问如何在使用起始值中的随机函数时将子字符串的长度限制为1。您可以使用
let
将随机数绑定到变量
(define pick-at-random
(lambda (s)
(let ((index (random (string-length s))))
(substring s index (+ index 1)))))
这里有一个不使用
子字符串
的替代答案,这样您就不需要将索引保存在let
绑定中。这是一个更实用(因此也是惯用)的问题解决方案:
(define (pick-at-random s) ; read the following lines from bottom to top
(string ; convert single character to string
(string-ref s ; access character in string, given an index
(random (string-length s))))) ; generate a random valid index in the string
(pick-at-random "word")
> "d" ; random result
前面的过程生成一个随机有效索引,然后在字符串中的该位置拾取字符。作为最后一步,它将单个字符转换为长度为1的字符串。前面的两个答案很好。或者,您可以将此问题分为两个问题:
- 开发函数“nth char”,该函数接受单词和索引,并返回包含单词第n个字符的字符串
- 开发“随机选取”功能,实现您所描述的功能。(顺便说一句,我认为像“random char”这样的名称比“pick at random”要好一些。)
(define (pick-at-random s) ; read the following lines from bottom to top
(string ; convert single character to string
(string-ref s ; access character in string, given an index
(random (string-length s))))) ; generate a random valid index in the string
(pick-at-random "word")
> "d" ; random result