php - Display the sorted array in 2 columns
I am trying to make it so that my code displays if entered array of numbers can be divided into 2 groups, and if yes then it displays"yes" or if no then"no. The yes or no part works fine, but if the code says yes then I want the code to also display the 2 columns with the numbers, I tried a lot but I just can't figure it out, please help.
function helper(&$arr, $n, $start, $lsum, $rsum) {
if ($start == $n)
return $lsum == $rsum;
if ($arr[$start] % 5 == 0)
$lsum += $arr[$start];
else if ($arr[$start] % 3 == 0)
$rsum += $arr[$start];
else
return helper($arr, $n, $start + 1, $lsum + $arr[$start], $rsum)
|| helper($arr, $n, $start + 1, $lsum, $rsum + $arr[$start]);
return helper($arr, $n, $start + 1, $lsum, $rsum);
}
function splitArray($arr, $n) {
return helper($arr, $n, 0, 0, 0);
}
$arr = array( 7,1, 7,3,4,6);
$n = count($arr);
if (splitArray($arr, $n))
print("Yes");
else
print("No");
Answer
Solution:
Provided you want to split them into two parts Replace your code at the bottom with...
$arr = array( 7,1, 7,3,4,6);
$n = count($arr);
list($group1, $group2) = array_chunk($arr, ceil(count($arr) / 2)); //Split the initial array into 2 if you want 3 just change 2 to 3 and so forth
if (splitArray($arr, $n)){
echo "Yes";
print_r($group1);
print_r($group2); //Each array assigned to new variable
} else {
echo "No";
}
Source