Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery multidimensional array shuffle random

I want to minimize my code from:

myArrayA = [1, 2, 3, 4, 5];
fisherYates(myArrayA);
myArrayB = [6, 7, 8, 9, 10];
fisherYates(myArrayB);
myArrayC = [11, 12, 13, 14, 15];
fisherYates(myArrayC);
myArrayD = [16, 17, 18, 19, 20];
fisherYates(myArrayD);
myArrayE = [21, 22, 23, 24, 25];
fisherYates(myArrayE);

To:

var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
fisherYates(multArr);

The output I want is like this:

[4,2,3,5,1],[7,10,6,9,8],[11,15,12,14,13],[18,17,16,20,19],[22,21,25,23,24]

I tried this code:
http://jsfiddle.net/arrow/yFn8U/

function fisherYates(myArray) {
var i = myArray.length, j, tempi, tempj;
if (i === 0) return false;
while (--i) {
    j = Math.floor(Math.random() * (i + 1));
    tempi = myArray[i];
    tempj = myArray[j];
    myArray[i] = tempj;
    myArray[j] = tempi;
}
}
var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
fisherYates(multArr);

But my code only randomizes the order of the chunks not the values in each chunk.
The output I want is like this:

[4,2,3,5,1],[7,10,6,9,8],[11,15,12,14,13],[18,17,16,20,19],[22,21,25,23,24]

I want each chunk inside the array to be in the same order but each chunk must be randomized.
Is there a way to do this with jQuery?
I also wonder how to get values from the shuffled/randomized array?
At the moment I get the values like this:

myArrayA[i]
myArrayB[i]
myArrayC[i]
myArrayD[i]
myArrayE[i]

I would guess I will get them with something like:

multArr [[0][i]];
multArr [[1][i]];
multArr [[2][i]];
multArr [[3][i]];
multArr [[4][i]];

Finally I wonder if minimizing the code will give better performance?

like image 205
ironarrow Avatar asked Dec 12 '22 15:12

ironarrow


1 Answers

If you simply want to run an operation over all the elements in an array, then you should use map or forEach. I'm sure jquery provides shims for these methods in older browsers. So if we assume you're using your original fisherYates function unaltered, we might have something like this:

var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
multArr.forEach(fisherYates);

On accessing the elements, you're almost right, but you have one set too many of brackets :

multArr[1]; // == [6, 7, 8, 9, 10]
multArr[1][3]; // == 9

I wouldn't speculate about the performance, if you're really worried you should put together a jsperf test case.

like image 100
Frances McMullin Avatar answered Dec 30 '22 23:12

Frances McMullin