javascript 如何在javascript中随机生成数字而不重复?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15585216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to randomly generate numbers without repetition in javascript?
提问by Shouvik
I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:
我想使用 javascript 随机生成 0 到 4 之间的每个数字,并且每个数字只能出现一次。所以我写了代码:
for(var l=0; l<5; l++) {
var randomNumber = Math.floor(Math.random()*5);
alert(randomNumber)
}
but this code is repeating the values. Please help.
但此代码正在重复这些值。请帮忙。
回答by Blender
回答by dfsq
One more way to do it:
另一种方法:
for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
console.log(random);
}
Don't know if it's even possible to make it more compact.
不知道是否有可能使它更紧凑。
Tests: http://jsfiddle.net/2m3mS/1/
测试:http: //jsfiddle.net/2m3mS/1/
Here is embed demo:
这是嵌入演示:
$('button').click(function() {
$('.output').empty();
for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
$('.output').append('<span>' + random + '</span>');
}
}).click();
.output span {
display: inline-block;
background: #DDD;
padding: 5px;
margin: 5px;
width: 20px;
height: 20px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<button>Run</button>
回答by Ingo Bürk
The answers given by Adil and Minko have a major problem (although Minko at least constrained it to a small set of numbers): They go over the same numbers over and over again.
Adil 和 Minko 给出的答案有一个主要问题(尽管 Minko 至少将其限制为一小组数字):他们一遍又一遍地重复相同的数字。
In that sense, a better method would be to create the array containing the possible values, shuffle it and then just pop elements off of it. This will require the complexity of shuffling the array, but it will get rid of the problem mentioned above.
从这个意义上说,更好的方法是创建包含可能值的数组,将其打乱,然后从中弹出元素。这将需要对数组进行洗牌的复杂性,但它会摆脱上面提到的问题。
var elements = [1, 2, 3, 4];
elements.shuffle(); // not a standard Javascript function, needs to be implemented
while( elements.length > 0 ) {
console.log( elements.pop() );
}
回答by Shouvik
Appreciate all your help. But probably another way to generate random number in a given max range can be implemented as per below.
感谢您的所有帮助。但可能另一种在给定最大范围内生成随机数的方法可以如下实现。
function generateRan(){
var max = 20;
var random = [];
for(var i = 0;i<max ; i++){
var temp = Math.floor(Math.random()*max);
if(random.indexOf(temp) == -1){
random.push(temp);
}
else
i--;
}
console.log(random)
}
generateRan();
回答by symlink
function getRanArr(lngth) {
let arr = [];
do {
let ran = Math.floor(Math.random() * lngth);
arr = arr.indexOf(ran) > -1 ? arr : arr.concat(ran);
}while (arr.length < lngth)
return arr;
}
const res = getRanArr(5);
console.log(res);
回答by Jijo Paulose
Generate random numbers without any range
生成没有任何范围的随机数
function getuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
}
return s4() + s4();
}
var uid = getuid();
alert(uid)
回答by Minko Gechev
If the range of random numbers is not very large you can use this:
如果随机数的范围不是很大,你可以使用这个:
var exists = [],
randomNumber,
max = 5;
for(var l = 0; l < max; l++) {
do {
randomNumber = Math.floor(Math.random() * max);
} while (exists[randomNumber]);
exists[randomNumber] = true;
alert(randomNumber)
}
回答by Aaron Plocharczyk
randojs.commakes this a simple one-liner:
randojs.com使这成为一个简单的单行:
randoSequence(4)
This will return an array of numbers from 0 through 4 in random order. You just need to add the following to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions as I've shown here.
这将按随机顺序返回一个从 0 到 4 的数字数组。您只需要将以下内容添加到 html 文档的头部,您就可以轻松地随心所欲地做任何想做的事。来自数组的随机值、随机的 jquery 元素、来自对象的随机属性,甚至像我在这里展示的那样防止重复。
<script src="https://randojs.com/1.0.0.js"></script>
回答by Fábio Ribeiro de Carvalho
Recursive Method in Type Script I used this in Angular app, it's similar in JS
Type Script 中的递归方法我在 Angular 应用程序中使用过它,它在 JS 中类似
private randomNumbers:Array<number> = []
private auxRandomColor:number
public avoidRepeatNumber():void{
let numberRandom:number = this.getRandomInt(0,9)
//sistema considera o zero como undefined, logo 0 zero é 100 depois converte pra zero
if(numberRandom === 0){
numberRandom = 100
}
let existNumber = this.randomNumbers.find( number => number === numberRandom)
if(!existNumber){
this.randomNumbers.push(numberRandom)
if(numberRandom === 100){
numberRandom = 0;
}
this.auxRandomColor = numberRandom
return
}
this.avoidRepeatNumber()
}
public getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
回答by All In One
var randomNumber = [];
for (var i = 0; i < 16; i++) {
var number = Math.floor(Math.random() * 4);
var genNumber = randomNumber.indexOf(number);
if (genNumber === -1) {
randomNumber.push(number);
}
}