Hướng dẫn shuffle array javascript es6 - xáo trộn mảng javascript es6

JavaScript là ngôn ngữ được sử dụng nhiều nhất để phát triển web và nó là ngôn ngữ dành cho trình duyệt, bạn có thể làm nhiều việc trong JavaScript ngoài kịch bản web như xây dựng trò chơi, máy chủ phụ trợ và những gì không. Vì vậy, nhu cầu xáo trộn một mảng sử dụng JavaScript có thể phát sinh cho số lượng ứng dụng để chọn ngẫu nhiên một số hành vi hoặc tạo mảng mới từ mảng hiện có, v.v. Trong các hướng dẫn này, chúng tôi sẽ thấy nhiều cách để xáo trộn JavaScript bằng cách sử dụng JavaScript hiện đại là ES6 hoặc lớn hơn. Vì vậy, hãy để xem làm thế nào chúng ta có thể chọn ngẫu nhiên một javascript mảng.

Hướng dẫn shuffle array javascript es6 - xáo trộn mảng javascript es6

Nội dung bài viết

  • 1 JavaScript mảng Shuffle bằng Array.Map và Math.Random Shuffle Array Javascript using Array.map and Math.random
  • 2 JavaScript mảng Shuffle bằng Array.Sort và Math.Random Shuffle Array Javascript using Array.sort and Math.random
  • 3 JavaScript mảng Shuffle bằng phương pháp Shuffle Lodash Shuffle Array Javascript using Lodash shuffle method
  • 4 Shuffle Một mảng JavaScript sử dụng thuật toán Shuffle của Fisher-Yates (còn gọi là Knuth) Shuffle an Javascript array using Fisher-Yates (aka Knuth) shuffle algorithm
  • 5 Mảng xáo trộn hoặc ngẫu nhiên bằng thuật toán Shuffle Durstenfeld Shuffle or randomize array using Durstenfeld shuffle algorithm

JavaScript mảng Shuffle bằng Array.Map và Math.Random

// using Array map and Math.random

const shuffledArr = array => array.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

Shuffle Array JavaScript bằng Array.Sort và Math.Random

// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());

JavaScript mảng shuffle sử dụng phương pháp shuffle lodash

// import or load lodash

const shuffledArr = _.shuffle([1, 4,6,7,10]);

Shuffle Một mảng JavaScript sử dụng thuật toán Shuffle của Fisher-Yates (còn gọi là Knuth)

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue,
    randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

const shuffledArr = shuffle(array);

Shuffle hoặc ngẫu nhiên mảng bằng thuật toán Shuffle Durstenfeld

Đây là phiên bản tối ưu của thuật toán Shuffle Fisher-Yates

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

const shuffledArr = shuffle(array);

Vì vậy, chúng tôi đã liệt kê 5 cách để xáo trộn javascript mảng bằng nhiều thuật toán nhưng cách được đề xuất là thuật toán shuffle durstenfeld hoặc fisher-yates (còn gọi là knuth) shuffle. Thuật toán Shuffle Durstenfeld nhanh hơn so với thuật toán Knuth Shuffle. Nó tùy thuộc vào bạn để sử dụng bất kỳ một trong những phương thức này để ngẫu nhiên một mảng dựa trên yêu cầu của bạn.Durstenfeld shuffle algorithm or Fisher-Yates (aka Knuth) shuffle. Durstenfeld shuffle algorithm is slighty faster compared to Knuth shuffle algorithm. It’s upto you to use any one of these methods to randomiz an array based on your requirement.

Tài nguyên:

  • https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
  • https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
  • https://1loc.dev/#shuffle-an-array

Shuffle mảng tại chỗ

Nội dung chính ShowShow

  • Các giải pháp khác
  • Làm thế nào để bạn xáo trộn các mục trong JavaScript?
  • Làm thế nào để bạn xáo trộn một chuỗi trong javascript?
  • Làm thế nào để bạn ngẫu nhiên một mảng trong javascript?
  • Bạn có thể xáo trộn một mảng không?

function shuffleArr (array){
    for (var i = array.length - 1; i > 0; i--) {
        var rand = Math.floor(Math.random() * (i + 1));
        [array[i], array[rand]] = [array[rand], array[i]]
    }
}

Mảng xáo trộn bằng cách sử dụng lớp ngẫu nhiên, chúng ta có thể lặp lại thông qua các phần tử mảng trong một vòng lặp.Sau đó, chúng tôi sử dụng lớp ngẫu nhiên để tạo số chỉ mục ngẫu nhiên.Sau đó hoán đổi phần tử chỉ mục hiện tại với phần tử chỉ mục được tạo ngẫu nhiên.Ở cuối vòng lặp, chúng ta sẽ có một mảng bị xáo trộn ngẫu nhiên. We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};

Shuffle mảng tại chỗ

Nội dung chính Show

Các giải pháp khác

Các giải pháp khác

Làm thế nào để bạn xáo trộn các mục trong JavaScript?

Làm thế nào để bạn xáo trộn một chuỗi trong javascript?

const getShuffledArr = arr => {
    if (arr.length === 1) {return arr};
    const rand = Math.floor(Math.random() * arr.length);
    return [arr[rand], ...getShuffledArr(arr.filter((_, i) => i != rand))];
};

Es6 tinh khiết, lặp đi lặp lại

// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());
0

Kiểm tra độ tin cậy và hiệu suất

// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());
1

Một số giải pháp trên trang này không đáng tin cậy (chúng chỉ ngẫu nhiên một phần cho mảng). Các giải pháp khác ít hiệu quả hơn đáng kể. Với

// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());
2

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
2 (xem bên dưới), chúng tôi có thể kiểm tra các chức năng xáo trộn cho độ tin cậy và hiệu suất.
function testShuffleArrayFun(getShuffledArrayFun){
    const arr = [0,1,2,3,4,5,6,7,8,9]

    var countArr = arr.map(el=>{
        return arr.map(
            el=> 0
        )
    }) //   For each possible position in the shuffledArr and for 
       //   each possible value, we'll create a counter. 
    const t0 = performance.now()
    const n = 1000000
    for (var i=0 ; i{countArr[key][value]++}
        )
    }
    const t1 = performance.now()
    console.log(`Count Values in position`)
    console.table(countArr)

    const frequencyArr = countArr.map( positionArr => (
        positionArr.map(  
            count => count/n
        )
    )) 

    console.log("Frequency of value in position")
    console.table(frequencyArr)
    console.log(`total time: ${t1-t0}`)
}

Các giải pháp khác chỉ để giải trí.

ES6 thuần khiết, đệ quy

ES6 thuần khiết sử dụng mảng.map

ES6 thuần túy bằng cách sử dụng mảng.Reduce

Giải pháp đơn giản có thể là:

// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());
6

Điều đó có phần hoạt động, bởi vì

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
3 là một số ngẫu nhiên có thể dương hoặc âm, do đó, hàm sắp xếp sắp xếp lại các yếu tố một cách ngẫu nhiên.

Nhưng vì hàm sắp xếp không có nghĩa là được sử dụng theo cách này, không phải tất cả các hoán vị đều có cùng một xác suất.

Ví dụ, hãy xem xét mã dưới đây. Nó chạy

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
4 1000000 lần và tính xuất hiện của tất cả các kết quả có thể có:
// using Array sort and Math.random

const shuffledArr = array => array.sort(() => 0.5 - Math.random());
5

Một kết quả ví dụ (phụ thuộc vào động cơ JS):

// import or load lodash

const shuffledArr = _.shuffle([1, 4,6,7,10]);
0

Chúng ta có thể thấy sự thiên vị rõ ràng:

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
0

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
5 và
const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
6 xuất hiện thường xuyên hơn nhiều so với những người khác.

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
1

Kết quả của mã có thể khác nhau giữa các công cụ JavaScript, nhưng chúng ta đã có thể thấy rằng phương pháp này là không đáng tin cậy.

Tại sao nó không hoạt động? Nói chung,

Làm thế nào để bạn xáo trộn các mục trong JavaScript?

Làm thế nào để bạn xáo trộn một chuỗi trong javascript?by using the sort() method. The JavaScript Array sort() method is used to sort the elements of an array. The method accepts a comparison function and performs a sort based on the value returned by that function.

Làm thế nào để bạn xáo trộn một chuỗi trong javascript?

Algorithm:...

Es6 tinh khiết, lặp đi lặp lại

Kiểm tra độ tin cậy và hiệu suất

Một số giải pháp trên trang này không đáng tin cậy (chúng chỉ ngẫu nhiên một phần cho mảng). Các giải pháp khác ít hiệu quả hơn đáng kể. Với

Sau đó, onvert mảng bị xáo trộn trở lại chuỗi bằng phương thức nối () ..

Làm thế nào để bạn ngẫu nhiên một mảng trong javascript?

Viết chức năng xáo trộn (mảng) mà xáo trộn (sắp xếp lại ngẫu nhiên) các phần tử của mảng.Nhiều lần chạy xáo trộn có thể dẫn đến các đơn đặt hàng khác nhau của các yếu tố.Ví dụ: LET ARR = [1, 2, 3];Shuffle (mảng);// mảng = [3, 2, 1] shuffle (mảng);// mảng = [2, 1, 3] shuffle (mảng);// mảng = [3, 1, 2] // .... Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // .... Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...

Bạn có thể xáo trộn một mảng không?

Mảng xáo trộn bằng cách sử dụng lớp ngẫu nhiên, chúng ta có thể lặp lại thông qua các phần tử mảng trong một vòng lặp.Sau đó, chúng tôi sử dụng lớp ngẫu nhiên để tạo số chỉ mục ngẫu nhiên.Sau đó hoán đổi phần tử chỉ mục hiện tại với phần tử chỉ mục được tạo ngẫu nhiên.Ở cuối vòng lặp, chúng ta sẽ có một mảng bị xáo trộn ngẫu nhiên. We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array. We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.