Skip to content
Advertisement

How to check possible all combinations of elements in an array that fullfil certain conditions?

I am currently writing (as an exercise) a simple political calculator that checks depending on how many seats each party has, possible majorities in the parliament.

I have created an object that holds the name as key and the seats as value, like so:

let testData = {
        "party1":19,
        "party2":29,
        "party3":10,
     }

I then use Object(entries) to move the data into an array:

let testArr = Object.entries(testData);

My question is, how can I check what possible combinations there are to get more than 30(seats) without duplication ?

From the above example, none of the parties get alone over 30, so some combinations are needed.

For example – party1 + party2 = 48 this is more than 30 so I save that result. But I wish to avoid having the result party2 + party1 = 48, because the order of the parties is irrelevant.

Advertisement

Answer

Not to prettiest but does the job, runs over the entries and then again to check them against each other. If the sum is over the threshold it will add them to the result with corresponding key.

let testData = {
  party1: 19,
  party2: 29,
  party3: 10,
};

const combinations = new Set();
const threshold = 30;

const result = {};

Object.entries(testData).map(([key1, value1]) => {
  return Object.entries(testData).map(([key2, value2]) => {
    if (key1 === key2) return; // party1 === party1 do nothing

    // take care of the doubles, party1 + party2 === party2 + party1
    const key = [key1, key2].sort().join(":");
    if (combinations.has(key)) return;
    combinations.add(key);

    // check if the sum is over the threshold
    const sum = value1 + value2;
    if (sum > threshold) result[key] = sum;
  });
});

console.log(result);

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement