Share the title
Title: Enter a positive integer n, return 1-n of n random, and do not repeat
For example, enter 4 and return 3, 2, 4, 1
1. Basic version
const a = 12
let b = new Array(a)
for(let i = 0; i < b.length; i++) {
const c = parseInt(Math.random() * a) + 1 b.indexOf(c) === -1 ? b[i] = c : i--
}
console.log(b)
Copy the code
function ccf(e) {
let ary = [];
let newAry = [];
for (let i=0; i<e;) {let origin = Math.round(Math.random()*e) % e + 1;
if(!ary[origin]){
ary[origin] = origin;
newAry.push(origin);
i++;
}
}
return newAry
}
Copy the code
2. Array subscript method
/ / method
const randomNum1 = n= > {
let arr = [];
let temp;
for (let i = 0; i < n; i++) {
// Generate an array of 1-n
arr[i] = i + 1;
}
for (let j = 0; j < n; j++) {
// Generate a random subscript
let index = Math.floor(Math.random() * n);
// Swap with the last number in the array, and subtract the total length of the array by one
// The index may be the same each time, but the number in the corresponding array is different
temp = arr[n - 1];
arr[n - 1] = arr[index];
arr[index] = temp;
n--;
}
return arr;
}
console.log(randomNum1(5));
/ / method 2
const randomNum2 = n= > {
let arr = [];
for (let i = 0; i < n; i++) {
// Generate an array of 1-n
arr[i] = i + 1;
}
// sort to generate a random decimal
arr.sort(function () {
return 0.5 - Math.random()
})
return arr;
}
console.log(randomNum2(5));
Copy the code
3. After the optimization
const fn = (n) => {
let i, range, num = new Array(n).fill(1).map((val, inx) => inx + 1);
for (i = n - 1; i > 0; i--) {
range = Math.floor(Math.random() * i);
[num[i], num[range]] = [num[range], num[i]];
}
return num;
}
fn(10);
Copy the code