Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ShuffleanArray #20

Open
xiaotiandada opened this issue Jan 19, 2021 · 0 comments
Open

ShuffleanArray #20

xiaotiandada opened this issue Jan 19, 2021 · 0 comments

Comments

@xiaotiandada
Copy link
Owner

2019-06-13 00:06:35

Shuffle an Array (carry)
Shuffle an Array

This snippet here uses Fisher-Yates Shuffling Algorithm to shuffle a given array.

Fisher-Yates Shuffling
Fisher-Yates Shuffling

example

function shuffle(arr) {
    var i,
        j,
        temp;
    for (i = arr.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;    
};

var a = [1, 2, 3, 4, 5, 6, 7, 8];
var b = shuffle(a);
console.log(b);
// [2, 7, 8, 6, 5, 3, 1, 4]

self

let arr = [1,2,3,4,5,6,7,8]
const shuffle = arr => {
  // 7 6 5 4 ... 2 1
  for(let i = arr.length - 1; i > 0; i--) {
    let temp = null
    let j = null
    // 0-7 0-6 0-5 ... ... 0-1
    j = Math.floor(Math.random() * (i + 1))
    temp = arr[j]
    arr[j] = arr[i]
    arr[i] = temp
  }
  return arr
}

console.log(shuffle(arr))

// [8, 4, 2, 3, 6, 1, 5, 7]
// [5, 4, 7, 3, 1, 6, 8, 2]
// [4, 5, 6, 8, 1, 2, 3, 7]
// [7, 5, 3, 4, 6, 8, 1, 2]
// [5, 7, 6, 3, 2, 1, 8, 4]
// [7, 6, 5, 3, 1, 8, 2, 4]
// [5, 6, 7, 8, 3, 1, 4, 2]
// [8, 3, 1, 7, 4, 5, 6, 2]
// [5, 8, 1, 4, 6, 7, 3, 2]
// [6, 5, 4, 2, 8, 3, 7, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant