Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into half with equal or approximately equal array sum

Tags:

arrays

php

Problem:

Array with numeric values needs to be split in half with approximately equal or if possible equal array sum. Number or order of elements in arrays is not important.

$probabilites = array(0.4, 0.15, 0.1, 0.1, 0.2, 0.2, 0.3); # 1.45

$probabilites[0] = array(0.4, 0.15, 0.1, 0.1); # 0.75
$probabilites[1] = array(0.2, 0.2, 0.3); # 0.7 

Any suggestions?

Thanks.

like image 738
Dejan Marjanović Avatar asked May 11 '26 16:05

Dejan Marjanović


2 Answers

Like this?

<?php
$in = array(0.4, 0.15, 0.1, 0.1, 0.2, 0.2, 0.3);

// Sort array decreasing
rsort($in, SORT_NUMERIC);

// Start with two empty arrays
$arr1 = $arr2 = array();

// Put the next value in the array in the array with the lowest sum
foreach ($in as $value)
  if (array_sum($arr2) > array_sum($arr1)) $arr1[] = $value; else $arr2[] = $value;

// Wrap in array (as in question)
$out = array($arr1,$arr2);
like image 95
Pelle Avatar answered May 13 '26 07:05

Pelle


Are you aware that this is the http://en.wikipedia.org/wiki/Knapsack_problem ?

And it's NP-Complete, so you can't do it fast.

For a small list it won't be too bad, if you have a larger list see some of the solutions on the wikipedia page.

like image 33
Ariel Avatar answered May 13 '26 08:05

Ariel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!