Last active
November 20, 2020 11:09
-
-
Save thenasim/31bee1e45d05ce17b2ac63101ba0fed0 to your computer and use it in GitHub Desktop.
Generate randomized new array from a given array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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