javascript - Optimal solution to balancing out a set of numbers -


so i'm writing side project , trying optimise:

given set of n numbers (e.g. [4, 10, 15, 25, 3]), want make each number same within given tolerance (i.e. if wanted exact, should 11.4 in above example).

we can add/remove 1 , add another. example, can -5 [3] , +5 [1] give [9, 10, 10, 25, 3].

the constraint have want minimal number of "transfers" between each number (e.g. if -3.6 [3], counts 1 "transfer").

not fussed performance (most can see going set of 50 numbers max) want keep transfers minimum.

we can assume tolerance +/- 1 start can dynamically change.

the goal of algorithm make sure each of numbers in list same within given tolerance. thus, if tolerance zero, numbers must equal average of values in list (which remain constant throughout algorithm). taking in account tolerance, numbers in list must belong inclusive interval [average - 0.5*tolerance, average + 0.5*tolerance].

the main iteration of algorithm involves retrieving maximum , minimum values , "transferring" enough maximum minimum value furthest average (this can either minimum or maximum) falls in required interval. process iterates till maximum , minimum values not more tolerance units away each other.

pseudocode algorithm follows:

target = average of values in list  while dist(max, min) > tolerance     x = maximum of dist(max, target) , dist(min, target)     transfer (x - 0.5*tolerance) units maximum minimum 

dist(a, b) can defined abs(a - b)

this algorithm runs in o(n^2) time on average, requiring bit more n iterations, n number of values.

this algorithm requires less half number of iterations naive sub-optimal approach of averaging out minimum , maximum values in each iteration takes.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -