topic
To sort an array out of order, it is required that each element will not fall into its original position and have the same probability of falling into other positions.
const arr = [1,2,3,4,5,6,7,8,9];
Ideas
For random rows: Use random numbers to get the subscript exchanged with the current position, which cannot be the current position.
prevent duplication: Suppose 1 and 2 are replaced, 2 and 3 are replaced, and 3 and 1 are replaced, then 1 will be "replaced to the original position". Here we use a flag mark to record the subsequent exchanged position. This position cannot be exchanged again. If 1 and 2 are exchanged, then position 2 cannot be exchanged (The main purpose is to prevent 2 from being replaced with the following one, and the latter one being replaced with 1.), even if 3 and 1 are swapped, the result is: 3 1 2
, no number will be swapped to its original position.
code
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function randerArr(arr) {
// 浅拷贝
let newArr = arr.slice(0),flag=[],n=arr.length
for(let i=0;i<n;i++){
// 如果这个下标之前被交换过则不再交换,防止重复
if(flag[i]) continue;
let temp=parseInt(Math.random()*n)
while(temp===i) temp=parseInt(Math.random()*n)
// 标记交换过的
flag[i]=true
flag[temp]=true
// 交换
let swap=newArr[i]
newArr[i]=newArr[temp]
newArr[temp]=swap
}
return newArr
}
console.log(randerArr(arr));
Here let newArr = arr.slice(0)
is a shallow copy, directly let newArr = arr
a deep copy: modifying arr
or newArr
will cause the arrays on both sides to change.
Reference: https://blog.csdn.net/qq_44697303/article/details/115438843