# How do I find the lowest combination of multiplied values

0 favourites
• 10 posts
From the Asset Store
Game with complete Source-Code (Construct 3 / .c3p) + HTML5 Exported.
• If I have an array and I want to find which combination of number pairs gives me the lowest total how would I do that?

For example if my array has the values 2,3,5 and 7.

2*3= 6, 5*7= 35. 35+6 = 41

2*5= 10, 3*7= 21. 21+10 = 31

2*7= 14, 3*5= 15. 15+14 = 29

So for these numbers the best combination of numbers is 2*7 and 3*5

Does that make sense?

• ## Try Construct 3

Develop games in your browser. Powerful, performant & highly capable.

Construct 3 users don't see these ads
• The min function returns the smallest value

Min(7, 4, 3) = 3

• Ok, that'll be really helpful thanks I'm still not sure how to get the program to run through every possible combination of the initial values though

• I'm on mobile so I can't really play around with it atm, but it you would have to make a loop that iterates through the array with a nested loop in a subevent so it will run each time through the main loop. You may need a second array to store the new values

• I think you will always get the lowest total by multiplying the biggest number by the smallest, then the next biggest number by the next smallest...

you shouldn't have to try every combination. Just sort them and match them up - first with last, second with second last...

• That works if it's groups of two but if it's 3 or 4 numbers multiplied together it doesn't work so well

• Turns out you don't need a recursive function to try all different orderings of the numbers. Instead just sort the list first and just multiply and sum them in order.

• How would that work? I mean like if my list is 1,2,3,4,5,6,7,8,9 in sets of 3 I would get something like

1*2*3 = 6

4*5*6 = 120

7*8*9 = 504

But there is definitely a better combination for that right? Or am I misunderstanding what you're saying

• I somehow missed you wanted the lowest value. Sorted it will give the highest value with pairs or probably triples. For the lowest you could reorder the array every possible way and try each one to see which is lowest.

I have a capx that does it that I can provide tomorrow if you want.

edit:

Here it is. It tries every combination and eventually gives the order with the lowest value:

https://www.dropbox.com/s/ajbvvy32cwd8m ... .capx?dl=0

The algorithm is O(n!) and the implementation is also slow. With 9 values it takes like 10 seconds on my machine. and gives this answer:

1*8*9 + 3*4*6 + 2*5*7 = 214

• Thanks ^-^ even if it's slow it saves me a lot of hand work

• 10 posts