-1

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?

imvain2
  • 15,480
  • 1
  • 16
  • 21
Parseltongue
  • 11,157
  • 30
  • 95
  • 160

1 Answers1

0

    var list_of_list = [["N", "B"], ["E", "B"], ["Y", "R"], ["R", "R"], ["A", "B"], ["U", "R"]];
    
    function shuffle(a){
         const arrlength = a.length;
         
         let shuffled = []; //array to be returned
         let numsused = []; //numbers chosen by rand
    
         while(shuffled.length < arrlength){
            let newnum = false;
            while(!newnum){
                const randm = Math.floor(Math.random() * arrlength);
                
                if(numsused.indexOf(randm) === -1){
                   shuffled.push(a[randm]);
                   newnum = true;
                   numsused.push(randm);
                }
            }
         }
         
         return shuffled;
    }
    
    console.log(shuffle(list_of_list));
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40