0

我在 javascript 中有三个数组,例如:

one = [1,2,3,4];
two = [5,6,7,8];
three = [9,10,11,12];

然后如果我打电话,shuffle(one,two,three)那么它可能会产生

one = [2,3,1,4];
two = [6,7,5,8];
three = [10,11,9,12];

例如,看看 2,6 和 10 stlil 是如何对齐的,并且所有三个都具有相同的索引?这就是我在其他列表中保持相互关联的数字的意思。

如何编写shuffle上面定义的函数?

4

1 回答 1

1
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)
});
于 2013-10-04T00:00:23.240 回答