Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The shuffle must be "uniform," meaning each item in the original array must have the same probability of ending up in each spot in the final array.
- Assume that you have a function getRandom(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.
- */
- function getRandom(floor, ceiling) {
- return Math.floor(Math.random() * (ceiling - floor + 1)) + floor;
- }
- function shuffle(array) {
- // Shuffle the input in place
- for(let i = array.length -1; i>0; i--){
- let randomIndex = getRandom(0, i);
- let temp = array[randomIndex];
- array[randomIndex] = array[i];
- array[i] = temp;
- }
- }
- const sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
- console.log('Initial array: ', sample);
- shuffle(sample);
- console.log('Shuffled array: ', sample);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement