zip = function() {
var args = [].slice.call(arguments, 0);
return args[0].map(function(_, i) {
return args.map(function(a) {
return a[i]
})
})
}
unzip = function(a) {
return a[0].map(function(_, i) {
return a.reduce(function(y, e) {
return y.concat(e[i])
}, [])
})
}
shuffle = function(a) {
for (var i = a.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = a[i];
a[i] = a[j];
a[j] = t;
}
return a;
}
z = unzip(shuffle(zip(one, two, three)))
one = z[0]
two = z[1]
three = z[2]
有点冗长,但有效...
另一种选择,在这种情况下可能更快:
range = function(n) {
for(var r = [], i = 0; i < n; i++)
r.push(i);
return r;
}
pluck = function(a, idx) {
return idx.map(function(i) {
return a[i];
});
}
r = shuffle(range(one.length))
one = pluck(one, r)
two = pluck(two, r)
three = pluck(three, r)
此外,最好有一个数组数组而不是三个变量:
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
];
r = shuffle(range(matrix[0].length));
matrix = matrix.map(function(row) {
return pluck(row, r)
});