1

I am trying to randomly shuffle an ember array without much success.

So far I use this snippet to shuffle the array:

Array.prototype.shuffle = function() {
    var len = this.length;
    var i = len;
     while (i--) {
        var p = parseInt(Math.random()*len,10);
        var t = this[i];
        this[i] = this[p];
        this[p] = t;
    }
};

And this snippet to compare two arrays:

Array.prototype.compareTo = function (array2){
    var array1 = this;
    var difference = [];
    $.grep(array2, function(el) {
        if ($.inArray(el, array1) == -1) difference.push(el);
    });
    if( difference.length === 0 ){
        var $i = 0;
        while($i < array1.length){
            if(array1[$i] !== array2[$i]){
                return false;
            }
            $i++;
        }
        return true;
    } else {
        return false;
    }
}

I use this to shuffle my array as long as it is the same as when i started:

while(array1.compareTo(array2) === true){
    array1.shuffle();
}

This loop however is an infinite loop, and I can't seem to find out why...

Thanks for your time.

Dries
  • 400
  • 5
  • 22

1 Answers1

1

You're shuffling the array in place, and then comparing it by reference to itself. This is causing the infinite loop.

Before your loop, make a copy of array1. Underscore.js is a good library that has this built in.

var array2 = _.clone(array1);
while(array1.compareTo(array2) === true){
    array1.shuffle();
}

It's worth mentioning that Underscore.js also has its own implementation of shuffle. It works differently though. It doesn't shuffle in place.

Jonathan Tran
  • 15,214
  • 9
  • 60
  • 67
  • I changed it to this: var shuffledAnswers = answers.slice(); Now the array is compared by value thanks for this! – Dries Sep 02 '13 at 07:18