javascript 5从0到20的随机非重复整数 [英] javascript 5 random non duplicating integers from 0 - 20

查看:66
本文介绍了javascript 5从0到20的随机非重复整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从0到20生成5个随机非重复整数的最佳方法是什么?

What's the best way to generate 5 random non duplicating integers from 0 - 20?

我在想,将Math.random与floor一起使用,将其循环5次,检查重复项,如果重复,则再次随机.

I'm thinking, use Math.random with floor, loop it 5 times, check for duplicates, if duplicate, random again.

你怎么走?

推荐答案

编辑:可以在 Knuth-Yates-Fisher随机播放对其进行随机播放. 不要使用幼稚的随机播放,请使用已知效果良好的随机播放.

Edit: A better solution that this or the others posted here can be found in this answer to this question when it was asked back in 2008. Summarizing: Generate an array (as Darin suggests in his answer below) and shuffle it using the Knuth-Yates-Fisher shuffle. Don't use a naive shuffle, use one that's known to have good results.

这几乎就是我要做的,是的.我可能会使用一个对象来跟踪已经拥有的整数,因为这很方便.例如:

That's pretty much how I'd do it, yes. I'd probably use an object to keep track of the integers I already had, since that's convenient. E.g.:

var ints = {};

然后,一旦您创建了一个新的随机数,请检查并保留它:

Then once you've created a new random number, check it and possibly keep it:

if (!ints[number]) {
    // It's a keeper
    ints[number] = true;
    results.push(number);
}

这篇关于javascript 5从0到20的随机非重复整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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