方案 - 生成随机 [英] Scheme - generate random

查看:42
本文介绍了方案 - 生成随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Scheme 中生成随机数?是否有特殊表格或我必须创建一个程序?如果是这样,我该怎么做?(我正在尝试创建一个名为 random-choice 的过程,该过程输入两种策略并随机返回一种.)

How do I generate random in Scheme? Is there a special form or would I have to create a procedure? And if so, how do I do that? (I'm trying to create a procedure called random-choice that inputs two strategies and returns one at random.)

推荐答案

该过程被调用,令人惊讶的是,random - 尽管确切的语法可能因使用的 Scheme 解释器而异(阅读文档!),但总体思路如下:

The procedure is called, surprisingly enough, random - although the exact syntax might be different depending on the Scheme interpreter in use (read the documentation!), but the general idea is as follows:

(random)
=> 0.9113789707345018

为了返回两个可能的值之一,这将在 Racket 中起作用:

For returning one of two possible values, this will do the trick in Racket:

(define (random-choice a b)
  (if (zero? (random 2)) a b))

请注意,传递给 random2 参数强制它随机返回两个可能值之一:01.因此,如果 (random 2) 计算结果为 0,则返回 a,否则返回 b.

Notice that the 2 argument passed to random forces it to randomly return one of two possible values: 0 or 1. So if (random 2) evaluates to 0 then a is returned, otherwise b is returned.

(random-choice 4 2)
=> 4
(random-choice 4 2)
=> 2

这篇关于方案 - 生成随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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