P23 (**) Extract a given number of randomly selected elements from a list.
来源:互联网 发布:深海逃生剧情 知乎 编辑:程序博客网 时间:2024/05/01 07:43
问题描述
The selected items shall be returned in a list.
sash> (rnd-select '(a b c d e f g h) 3) -> (e d a)
Hint: Use the built-in random number generator and the result of problem P20.
解法
(import (srfi 27))(define rnd-select (lambda (ls n) (let f ([s ls] [n n]) (cond [(zero? n) '()] [else (let ([i (random-integer (length s))]) (cons (list-ref s i) (f (remove-at s (+ i 1)) (- n 1))))]))))
需要说明几点:
- R7RS没有自带随机数的函数,这里使用了SRFI-27中的random-integer n
产生[0,n)
间的随机整数;
- 使用了P20定义的remove-at
函数,该函数指定的列表索引从1开始,而list-ref
指定的列表索引从0开始,所以索引需要做简单转换。
1 0
- P23 (**) Extract a given number of randomly selected elements from a list.
- P14 (*) -P15 (**)Duplicate the elements of a list,Duplicate the elements of a list a given number of
- Pick Several Elements From a Vector Randomly
- P15 (**) Replicate the elements of a list a given number of times.
- CareerCup Randomly return a number inside of this range
- P18 (**) Extract a slice from a list
- P18 (**) Extract a slice from a list.
- Selecting Rows Randomly from a Large Table
- Binary representation of a given number
- All factors of a given number
- Extracting Unique Elements From a List
- jar - user of jar command to list/extract file from a jar file
- P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.
- P14 (*) Duplicate the elements of a list.
- CareerCup Find all the conflicting appointments from a given list of n appointments.
- Write efficient code for extracting unique elements from a sorted list of array. e.g.
- LeetCode 17.Letter Combinations of a Phone Number & 19.Remove Nth Node From End of List
- MACRO of a method of loop list for visit elements
- 初识AutoMapper
- first
- 九度oj 1437 贪心
- 递归转换为二进制
- 类与接口
- P23 (**) Extract a given number of randomly selected elements from a list.
- 一维/二维动态数组分配(C语言)
- TCP/IP、Http、Socket的区别
- C语言 printf函数的返回值
- Java 创建不可变对象-final关键字的使用总结
- 为Java说句公道话
- OpenGL es gluLookAt 函数
- jquery实战(1)
- 61. Implement Stack using Queues