In javascript, I am little bit confused that how to get the actual and accurate probability of shuffling an object in an array. For example
var numberOfOrder=[
{
id:1
},
{
id:2
},
{
id:3
}
]
From above example The above object can be manipulated in 6 ways By finding the factorial numberOfOrder.length;
But what is the actual way to shuffle that object in an array.
My Try
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
}
But the above function won't return accurate value if I run that function 6 times it returning Duplicate Values
What is the correct function to do it
You have to understand the difference between probability and permutations. The second term comes from combinatorics. There are some algorithms that allow to get all possible permutations of array items. Here is one of them:
Update
The recursive algorithm is implemented above. The function
permutations
gets an array and for each item recursively gets all permutations beginning with current item. At each step of recursion the array is shorter by one item (minus the current item) and at the last step single element array is not being processed because permutations are not available anymore.Also some comments added to the code.
The last line is just the test to get all permutations of array
[1, 2, 3]
and to show them viaalert
. To get more illustrative view all found permutations are glued with new line symbol (.join("\n")
).