-2

私は本当にこれを理解することはできません。

どうすればこれを回すことができますか:

varAllMix = [[1,2], [3,4], [1,4], [5,6], [7,2], [8,5], [9,10], [11,6]];

これに:

varComGroup = [[1,2,3,4,7],[5,6,8,11],[9,10]]

例:は、共通の値による[1,2,3,4,7]マージの結果です:[1,2], [3,4], [1,4], [7,2]

[1,2] + [1,4] -> [1, 2, 4]
[1, 2, 4] + [3,4] -> [1, 2, 3, 4]
[1, 2, 3, 4] + [7, 2] -> [1, 2, 3, 4, 7]
4

2 に答える 2

1

allMixこれにより、非常に効率的に実行できます (タプルごとに 2 つ以上の値もサポートします)。

var AllMix = [[1,2], [3,4], [1,4], [5,6], [7,2], [8,5], [9,10], [11,6]];

var ComGroup = [],
    lookup = {}; // a lookup table for sets in ComGroup per value
for (var i=0; i<AllMix.length; i++) {
    var sets = [], // sets in ComGroup that contain one of the tuple values
        add = []; // new, yet unknown values
    for (var j=0, l=AllMix[i].length; j<l; j++) {
        var val = AllMix[i][j];
        if (val in lookup) {
            if (sets.indexOf(lookup[val]) == -1)
                sets.push(lookup[val]);
        } else
            add.push(val);
    }
    var merge = sets.shift(), // the set to merge into (or add values)
        addFrom; // the number of values in merge that are known to lookup
    if (merge) {
        addFrom = merge.length;
        if (add.length) sets.push(add); // add the new values to the merged sets
    } else { // no set was found in lookup that contains numbers from the tuple
        ComGroup.push(merge = add); // make the new numbers the new set
        addFrom = 0;
    }
    for (var j=0; j<sets.length; j++) // merge all sets into merge
        merge.push.apply(merge, sets[j].splice(0)); // and empty them
    for (var l=merge.length; addFrom<l; addFrom++) // for all new numbers
        lookup[merge[addFrom]] = merge; // update the set lookup table
}
ComGroup = ComGroup.filter(function(set) {
    // sort each set numerically and remove the empty ones
    return set.sort(function(a,b){return a-b;}).length;
});
于 2013-09-09T16:45:21.250 に答える