如何在Math Random中每次返回一个随机数。

时间:2018-03-14 02:40:51

标签: arrays random swap alexa-skills-kit

我刚才有一个问题,

我一直在建立alexa技能。 (概念是随机化积极性) 但不知怎的,它继续返回相同的句子.... 这是我的代码......

` for (var j = 0; j < index; j++){
        var rand =  Math.floor(Math.random() * index);
        index -= 1;

        var temp = indexList[index];
        indexList[index] = indexList[rand];
        indexList[rand] = temp;

    }`// I also swap the words so It would sure not to return the same but somehow  it happens..

目前索引约为15个字符串... 我的问题是如何让它尽可能随意?

1 个答案:

答案 0 :(得分:0)

你只是试图改变阵列,对吗?看Fisher-Yates shuffle.你几乎已经做了同样的事情。

我试过这个并且工作正常。

var indexList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var rand;
var temp;

for (let i = 0; i < indexList.length; i++) {
  rand = Math.floor(Math.random() * (i + 1));
  temp = indexList[i];
  indexList[i] = indexList[rand];
  indexList[rand] = temp;
  console.log(indexList);
}

它打印了以下内容,表明它正在逐步改变阵列:

> Array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [2, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [3, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 1, 5, 3, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 7, 1, 9, 10, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 9, 1, 7, 10, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 9, 1, 10, 7, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 9, 1, 10, 7, 11, 12, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 9, 1, 12, 7, 11, 10, 13, 14, 15]
> Array [4, 6, 5, 3, 2, 8, 9, 1, 12, 7, 11, 10, 13, 14, 15]
> Array [4, 6, 14, 3, 2, 8, 9, 1, 12, 7, 11, 10, 13, 5, 15]
> Array [4, 6, 15, 3, 2, 8, 9, 1, 12, 7, 11, 10, 13, 5, 14]