I have the following problem:
I have 3 arrays say a, b, c each one of them has a size in between 0 and 20.
Then I have another array target that have a size of 20(as a maximum) and has to be filled up with the values contained in a, b, c.
The ideal distribution in target should be 8 elements from a, 6 from b and 6 from c.
However, in case I don't have enough element in one of the three array I need to add elements from the other two, in a balanced manner.
For instance: if c has only 4 elements, then target needs to be filled up with 9 elements of a, 7 elements of b and the 4 coming form c.
What I am trying to find is the wanted size of each of the three original arrays a, b c, so that later on I'll be able to add the elements to target.
I have to do this using php and I am struggling a bit. I came up with this solution:
<?php
// count of the elements in the three original arrays
$a_count = 20;
$b_count = 20;
$c_count = 4;
// size of the target array
$total_count = 20;
if($a_count + $b_count + $c_count < 20)
$total_count = $a_count + $b_count + $c_count;
// the size desired at the end of the process
$a_wanted_size = 0;
$b_wanted_size = 0;
$c_wanted_size = 0;
$a_more = true;
$b_more = true;
$c_more = true;
$total = 0;
if($a_count > 8){
$a_wanted_size = 8;
$total += $a_wanted_size;
}
if($b_count > 6){
$b_wanted_size = 6;
$total += $b_wanted_size;
}
if($c_count > 6){
$c_wanted_size = 6;
$total += $c_wanted_size;
}
if($a_count <= 8){
$a_wanted_size = $a_count;
$total += $a_count;
$a_more = false;
}
if($b_count <= 6){
$b_wanted_size = $b_count;
$total += $b_count;
$b_more = false;
}
if($c_count <= 6){
$c_wanted_size = $c_count;
$total += $c_count;
$c_more = false;
}
echo("total ".$total);
while($total < $total_count){
if($a_more == true && $total < $total_count){
$a_wanted_size++;
$total++;
}
if($b_more == true && $total < $total_count){
$b_wanted_size++;
$total++;
}
if($c_more == true && $total < $total_count){
$c_wanted_size++;
$total++;
}
}// end of while
echo"RESULT <br>";
echo("a ".$a_wanted_size."<br>");
echo("b ".$b_wanted_size.'<br>');
echo('c '.$c_wanted_size.'<br><br>');
echo("total ".$total);
However, it looks a bit too complex for me, and maybe error prone, any better idea? Thank you!
a,b, andcthe same arrays aslocal,national, andtravel?