dimanche 20 janvier 2019

Randomly choose combinations so that each element is represented exactly twice

I'm trying to choose combinations so that each element is represented exactly twice. Ideally it should choose the combinations at random, so that on subsequent runs it doesn't always produce the same result.

Example set

[1, 2, 3, 4, 5]

All possible combinations are:

[[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

I need to get something like:

[[1,2], [1,3], [2,5], [3,4], [4,5]]

var set = [1, 2, 3, 4, 5];
var all = [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], 
           [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]];

var combs = {};

var counts = {};
set.forEach((num) => {
    counts[num] = 0;
});

for(let i = 0; i < set.length; i++){
    let compare = set[i];
    for(let j = 0; j < all.length; j++){
        let combination = all[j];
        let left = all[j][0];
        let right = all[j][1];

        if(combination in combs === false) {
            if((counts[left] < 2 && counts[right] < 2)) {
                if(compare === left || compare === right) {
                    counts[left]++;
                    counts[right]++;
                    combs[combination] = combination;
                }
            }
        }
    }
}

console.log("counts");
console.log(counts);
console.log("Combinations");
console.log(combs);

I'm experiencing a problem where, for a set of length 5, only the first 3 get represented twice, and the remaining 2 is represented once.

Also I know that this will not be random currently. I would really like to make it randomly choose the combinations.

Actual output

"counts"
[object Object] {
    1: 2,
    2: 2,
    3: 2,
    4: 1,
    5: 1
}
"Combinations"
[object Object] {
    1,2: [1, 2],
    1,3: [1, 3],
    2,3: [2, 3],
    4,5: [4, 5]
}




Aucun commentaire:

Enregistrer un commentaire