javascript - equal an array of numbers in the shortest way -


i have array contain random numbers:

var equalme = [math.random(), math.random(), math.random(),math.random()]; 

now lets numbers chosen are: 0.4, 0.3, 0.2, 0.1. need find way make algorithm, equal each number 0.25 (since (0.4+0.3+0.2+0.1)/4 = 0.25) , i'm trying in fastest way possible withdrawing value each number in array another.

so example shortest way withdraw equalme[0] value of 0.15 equalme[3] , withdraw value of 0.05 equalme[1] equalme[2] each number in array same (0.25).

my question how can make code, can find shortest way withdraw values when size of array can given choice (not 4 numbers) , values in array random, numbers equal lowest withdraws possible?

please note: need code money exchanging program bitcoin wallets each time withdraw money 1 wallet lose fee need withdraw money 1 wallet lowest amount of withdraws possible wallets have same value giving total money

edit: find average value of set of numbers, calculate difference each of these compared number , sort them greatest difference, start divvying values each equal average value. you're matching biggest differences 1 one (and sending of remainder next item in line)

========
example 1: 0.4, 0.3, 0.45, 0.25 (average 0.35)

the differences 0.1 (0.25), -0.1 (0.45), 0.05 (0.3), , -0.05 (0.4), making 2 transactions needed 0.35 values.
1st transaction = 0.45, move - 0.1 0.25 = 0.35 both
2nd transaction = 0.4, move -.05 0.3 = 0.35 both

========
example 2: 0.32, 0.47, 0.12, 0.56 (average = 0.3675)

differences (sorted in order) 0.2475 (0.12), -0.1925 (0.56), 0.1025 (0.47), 0.0475 (0.32)
1st transaction = 0.56, move 0.1925 0.12 (now equal 0.3125)
2nd transaction = 0.47, move 0.0550 0.12 (now equal 0.3675)
3rd transaction = 0.47, move 0.0475 0.32 (now equal 0.3675

you might have more luck using median value versus average in cases, set both, test 1 uses least transactions, commit 1 least transactions.

original
instead of handling programmatically, why not mathematically?

for instance, if randomly generate numbers, change values 0.25 want.

if total of 4 random values equals 1.4 (0.4, 0.3, 0.45, 0.25), 0.25/1.4 ~0.17 multiply each of values 0.17 reduce value total 0.25.

(0.4 x 0.17) + (0.3 x 0.17) + (0.45 x 0.17) + (0.25 x 0.17) = ~0.25


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -