如何在 javascript 中获得不重复值的情况下对数组进行洗牌的概率

How get the probability of shuffling an array without getting duplicate Values in javascript

在javascript中,我有点困惑如何获得对数组中的对象进行洗牌的实际准确概率。 例如

var numberOfOrder=[
  {
    id:1 
  },
  {
    id:2 
  },
  {
    id:3 
  }
]

从上面的例子可以通过找到阶乘 numberOfOrder.length;

以 6 种方式操作上面的对象

但是在数组中随机排列该对象的实际方法是什么。

我的尝试

function newShuffle(value) {
    for(var i = value.length-1;i >=0; i--){
        var randomIndex = Math.floor(Math.random()*(i+1));
        var itemAtIndex = value[randomIndex];

        value[randomIndex] = value[i];
        value[i] = itemAtIndex
    }
    return value
}

但是如果我 运行 函数是它的 6 倍 returning 重复值

,上面的函数将不会 return 准确值

正确的函数是什么

你必须了解概率和排列之间的区别。第二项来自组合学。有一些算法允许获取数组项的所有可能排列。这是其中之一:

function permutations(items) {
    // single item array - no permutations available
    if (items.length == 1) return [items];
    var combos = [];
    for (var i = 0; i < items.length; i++) {
        // first - the current item, rest - array without the current item
     var first = items[i], rest = items.slice(0);
        rest.splice(i, 1);
        // getting permutations of shorter array and for each of them...
        permutations(rest).forEach(function(combo){
            // prepend the current item
            combo.unshift(first);
            // save the permutation
            combos.push(combo);
        });
    }
    return combos;
}

alert(permutations([ 1, 2, 3 ]).join("\n"));

更新

上面实现了递归算法。函数 permutations 获取一个数组,并为每个项目递归地获取从当前项目开始的所有排列。在递归的每一步,数组都缩短了一项(减去当前项),并且在最后一步,单个元素数组没有被处理,因为排列不再可用。

还在代码中添加了一些注释。

最后一行只是获取数组 [1, 2, 3] 的所有排列并通过 alert 显示它们的测试。为了获得更多说明性视图,所有找到的排列都用换行符号 (.join("\n")) 粘贴。

如评论和上述答案所述,您需要进行排列操作。然而,有许多方法可以获得数组的排列。有关排列的更多信息,我建议您查看 Permutations in JavaScript 主题。

另一方面,与动态编程方法相比,递归方法总是慢得多。最近我想出了一个排列算法,它似乎是所有算法中最快的。 Check it up