【发布时间】:2014-04-23 12:43:06
【问题描述】:
我有以下问题:
我有 3 个数组,比如 a、b、c,每个数组的大小都在 0 到 20 之间。
然后我有另一个数组target,其大小为20(最大值),并且必须用a、b、c 中包含的值填充。
target 中的理想分布应该是 a 中的 8 个元素,b 中的 6 个元素和 c 中的 6 个元素。
但是,如果我在三个数组之一中没有足够的元素,我需要以平衡的方式添加其他两个数组中的元素。
例如:如果c只有4个元素,那么target需要用a的9个元素、b的7个元素和c的4个元素来填充。
我想要找到的是三个原始数组a、bc 中每一个的所需大小,以便稍后我可以将元素添加到target。
我必须使用php 来做到这一点,而且我有点挣扎。我想出了这个解决方案:
<?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);
但是,它看起来对我来说有点太复杂了,而且可能容易出错,有更好的主意吗? 谢谢!
【问题讨论】:
-
a、b和c是否与local、national和travel相同的数组?