Skip to content

Instantly share code, notes, and snippets.

@thenasim
Last active November 20, 2020 11:09
Show Gist options
  • Save thenasim/31bee1e45d05ce17b2ac63101ba0fed0 to your computer and use it in GitHub Desktop.
Save thenasim/31bee1e45d05ce17b2ac63101ba0fed0 to your computer and use it in GitHub Desktop.
Generate randomized new array from a given array
// normal version
const random = ([...arr]) => {
let rand;
for (let i = 0; i < arr.length; i++) {
rand = Math.floor(Math.random() * (arr.length - i) + i);
[arr[i], arr[rand]] = [arr[rand], arr[i]];
}
return arr;
}
// optimized version
const randomizeOptimized = ([...arr]) => {
const len = arr.length;
for (let i = 0; i < Math.ceil(len / 2); i++) {
const rand = Math.floor(Math.random() * (len - i) + i);
[arr[i], arr[rand]] = [arr[rand], arr[i]];
}
return arr;
}
const arr = [1,2,3,4,5,6,7,8,9,10];
const result = random(arr);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment