mercredi 23 septembre 2020

How to shuffle a list of lists in javascript [duplicate]

Let's say I have a list of lists in Javascript like so:

var list_of_list = [["N", "B"], ["E", "B"], ["Y", "R"], ["R", "R"], ["A", "B"], ["U", "R"]]

I'd like to randomize the first-level ordering of the lists without randomizing inside the lists. So, for example,

shuffle(list_of_lists) 
> [["E", "B"], ["R", "R"], ["Y", "R"], ["N", "B"], ["U", "R"], ["A", "B"]]

Is one possible random shuffle since it preserves the ordering of the nested lists while randomizing the top-level lists.

I've tried a number of different approaches, but can't seem to get shuffling to occur. For example, none of these standard approaches to shuffling work:

var list_of_list = [["N", "B"], ["E", "B"], ["Y", "R"], ["R", "R"], ["A", "B"], ["U", "R"]]
      function shuffle(a) {
                var j, x, i;
                for (i = a.length - 1; i > 0; i--) {
                    j = Math.floor(Math.random() * (i + 1));
                    x = a[i];
                    a[i] = a[j];
                    a[j] = x;
                }
                return a;
            }
      
        function shuffle_2(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;
        }

     list_of_list2 = list_of_list.sort(func);  
     function func(a, b) {  
                return 0.5 - Math.random();
            } 
            
            
console.log(list_of_list2.join("|"));
console.log(shuffle(list_of_list).join("|"));
console.log(shuffle_2(list_of_list).join("|"));

What is the right way to do this?




Aucun commentaire:

Enregistrer un commentaire