K
K
Konstantin Kitmanov2014-12-30 22:17:24
Algorithms
Konstantin Kitmanov, 2014-12-30 22:17:24

How to arrange six numbers so that the sum of the first three is approximately equal to the sum of the rest?

The task is to draw a donut chart beautifully. The chart always consists of six sectors; on the right and on the left - three legends with pointers. Accordingly, in order for it all to be more or less symmetrical, it is necessary to feed the library responsible for rendering the chart with the data in the correct order. That is, so that (a 0 + a 1 + a 2 ) - (a 3 + a 4 + a 5 ) is the minimum of all possible.
One could simply go through all possible permutations of an array of six elements, but this, EMNIP, is 6! == 720 permutations, and it happens in the browser, in JS, and in a place where the brakes are not allowed in any way.
The sum of the numbers will obviously be equal to 100 (because 100%).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vans239, 2014-12-30
@k12th

Something you exaggerated the number of necessary permutations. The choice of the left triple uniquely determines the choice of the right triple (as well as its sum). Therefore, in total, it is necessary to sort out 6! / (3! * 3!) = 20. And this is already not enough

V
Vladlen Grachev, 2014-12-30
@gwer

Sort and take the even elements in the first sample, and the odd ones in the second. Not the fact that this will give the best result, but simple, fast and the first thing that comes to mind.
The result will be closer to the desired one if in each set we take in turn, first an even element, then an odd one. Let's say there is a sorted set: 1,2,3,4,5,6.
We take: (1, 4, 5), (2,3,6). This is already better than (1, 3, 5), (2, 4, 6). Since we do not take each time in a set with even elements a obviously larger element, but alternate.
If the numbers add up to something specific (100 or 1, for example), then you can try to implement a directed search for the set that is closest to half of the sum.

M
Mrrl, 2014-01-06
@Mrl

Sort in descending order, then put the first two elements in different heaps, and each next one - in one of the heaps where the sum is currently less. It will not always work (for example, 25,25,20,20,9,1), but it does not require enumeration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question