javascript - 仅使用一个函数 Rand100() 的 1-20 随机数组

标签 javascript algorithm

我必须得到一个1-20的数组,不重复,按随机顺序排列。我能使用的只是一个函数 Rand100(),它给出 1-100 之间的随机数?如果可能,请用 JavaScript 回答。

最佳答案

这应该为您提供一个起点。我使用 Math.random 而不是 Rand100 - 但它们应该会产生类似的结果。 array_to_randomize 是包含要随机化的元素的数组。
random 包含随机化的结果。

    /* Array to Randomize */
var array_to_randomize = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"]
/* Results */
var random = [];

var j = 0, 
        i = array_to_randomize.length;

while (i > 0){
    j = Math.random() * array_to_randomize.length;
    random.push(array_to_randomize.splice(j,1))
    i = array_to_randomize.length;

}

random.forEach(function(value,index){console.log("index: " +  index + " value: " + value)})

关于javascript - 仅使用一个函数 Rand100() 的 1-20 随机数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143234/

相关文章:

javascript - 从 html 字符串名称值对中获取属性

javascript - 我们可以在 Controller 中访问 Ember.TEMPLATES 吗?

c - 提高union-find的效率

javascript - jquery : How to use the . css() 方法

javascript - 用于在 javascript 验证中接受所有类型电话号码的正则表达式

javascript - Symfony 2.6 - 将 jQuery 文件添加到 Twig

algorithm - 在平均 n + log n 比较中找到最大和第二大的 n 个数字

performance - 递归伪代码的时间复杂度

算法 - 将文件夹分成组

algorithm - 复杂求根算法