Continuing to my comments
In the title of the topic, you indicate that if they are not absolutely equal, then they are as close to equality as possible. Then, in PHP I did the following:
- I counted the sum of the array values ββand divided it into two
- Sorted array descending values
- Enumerating sorted massi
array_1 = 0;
array_m2 = 0;
if (sum of array1 <= sum of array2 || sum of array2> = gender of total_sum) {
Π΄ΠΎΠ±Π°Π²ΠΈΡΡ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π² ΠΌΠ°ΡΡΠΈΠ²1 ΡΡΠΌΠΌΠ°_ΠΌΠ°ΡΡΠΈΠ²Π°1 += Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅;
} otherwise {
Π΄ΠΎΠ±Π°Π²ΠΈΡΡ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π² ΠΌΠ°ΡΡΠΈΠ²2 ΡΡΠΌΠΌΠ°_ΠΌΠ°ΡΡΠΈΠ²Π°2 += Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅;
}
The code in PHP (you can check it here - http://writecodeonline.com/php/ ):
$arr = array(10,68,30,28,34,74,52,20,176,18,86,14,22,4); // ΠΈΡΡ
ΠΎΠ΄Π½ΡΠΉ ΠΌΠ°ΡΡΠΈΠ² rsort($arr,SORT_NUMERIC); // ΡΠΎΡΡΠΈΡΡΠ΅ΠΌ ΠΏΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΡΠΌ Π² ΠΎΠ±ΡΠ°ΡΠ½ΠΎΠΌ ΠΏΠΎΡΡΠ΄ΠΊΠ΅ $halfSum = intval(array_sum($arr) / 2); // Π²ΡΡΡΠΈΡΡΠ²Π°Π΅ΠΌ ΡΡΠΌΠΌΡ Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ ΠΈ Π΄Π΅Π»ΠΈΠΌ Π½Π° Π΄Π²Π΅ ΠΏΡΠΈΠΌΠ΅ΡΠ½ΠΎ ΡΠ°Π²Π½ΡΠ΅ ΡΠ°ΡΡΠΈ $arr_first = array(); // ΠΏΠ΅ΡΠ²ΡΠΉ ΠΌΠ°ΡΡΠΈΠ² $arr_second = array(); // Π²ΡΠΎΡΠΎΠΉ ΠΌΠ°ΡΡΠΈΠ² $sum1 = 0; // ΡΡΠΌΠΌΠ° ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ ΠΌΠ°ΡΡΠΈΠ²Π° Π΄Π»Ρ ΡΡΠ°Π²Π½Π΅Π½ΠΈΡ $sum2 = 0; // ΡΡΠΌΠΌΠ° Π²ΡΠΎΡΠΎΠ³ΠΎ ΠΌΠ°ΡΡΠΈΠ²Π° Π΄Π»Ρ ΡΡΠ°Π²Π½Π΅Π½ΠΈΡ // ΠΏΠ΅ΡΠ΅Π±ΠΈΡΠ°Π΅ΠΌ ΠΎΡΡΠΎΡΡΠΈΡΠΎΠ²Π°Π½Π½ΡΠΉ ΠΈΡΡ
ΠΎΠ΄Π½ΡΠΉ ΠΌΠ°ΡΡΠΈΠ² foreach($arr as $val){ // ΡΡΠΌΠΌΠ° ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ ΠΌΠ°ΡΡΠΈΠ²Π° ΠΌΠ΅Π½ΡΡΠ΅ Π²ΡΠΎΡΠΎΠ³ΠΎ // ΠΈ ΡΡΠΌΠΌΠ° Π²ΡΠΎΡΠΎΠ³ΠΎ ΠΌΠ°ΡΡΠΈΠ²Π° Π±ΠΎΠ»ΡΡΠ΅ ΠΈΠ»ΠΈ ΡΠ°Π²Π½Π° ΠΏΠΎΠ»ΠΎΠ²ΠΈΠ½Π΅ ΠΎΠ±ΡΠ΅ΠΉ ΡΡΠΌΠΌΡ // ΡΠΎ ΠΎΡΠ΅ΡΠ΅Π΄Π½ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΡΡΡ Π² ΠΏΠ΅ΡΠ²ΡΠΉ ΠΌΠ°ΡΡΠΈΠ² // Π² ΠΈΠ½ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ - Π²ΠΎ Π²ΡΠΎΡΠΎΠΉ ΠΌΠ°ΡΡΠΈΠ² if($sum1 <= $sum2 || $sum2 >= $halfSum){ $arr_first[] = $val; $sum1 += $val; } else { $arr_second[] = $val; $sum2 += $val; } } //Π²ΡΠ²ΠΎΠ΄ΠΈΠΌ ΡΡΠΌΠΌΡ ΠΎΠ±ΠΎΠΈΡ
ΠΌΠ°ΡΡΠΈΠ²ΠΎΠ² echo array_sum($arr_first).'<br />'.array_sum($arr_second);
Of course, Iβm far from sure that it works correctly, but Iβve tested it several times and it seems to have done everything perfectly.