This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; P23 (**) Extract a given number of randomly selected elements from a list. | |
;; The selected items shall be returned in a list. | |
;; Example: | |
;; * (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. | |
#lang racket | |
(provide rnd-select) | |
(require "p03.ss") | |
(require "p20.ss") | |
(define (rnd-select lst num) | |
(let loop ((lst lst) (selected 0) (acc '())) | |
(if (= num selected) | |
(reverse acc) | |
(let ((rand-pos (+ (random (length lst)) 1))) | |
(loop (remove-at lst rand-pos) | |
(+ selected 1) | |
(cons (element-at lst rand-pos) acc)))))) |
0 件のコメント:
コメントを投稿