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:

JavaScript

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

JavaScript

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.

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