【问题标题】:How to merge two sets of data/array dynamically based on their count如何根据计数动态合并两组数据/数组
【发布时间】:2015-05-12 19:00:17
【问题描述】:

所以,我有这样的要求,我有两组数据(存储在数组中,但可以是任何东西)。我想要做的是我想将这两个集合加在一起,以便最终结果计数为 10。

场景是:

  1. 这两个集合最初可以有超过 5 个(或 10 个)。在这种情况下,这很容易 - 我只需从每组中取出 5 个并将它们加在一起并显示

  2. 任何一组都可能小于 5。在这种情况下,我应该采用该组中可用的任何内容。在另一组中,我应该取多少才能使总数达到 10,如果另一组的计数很低以至于无法使总数达到 10,那么我应该全部拿走并显示我得到的任何东西。

基于此要求,我正在尝试编写一个逻辑,该逻辑将为我提供每组所需的计数,但是 if-else-if-else 变得太复杂了,我认为我可能做错了。谁能帮我创建一个更简单的逻辑来做我需要的事情?

我目前的(不完整和复杂的)逻辑是:

if($set1Count >= 5)
{
    $requiredSet1Count = 5;
    if($set2Count >= 5)
    {
        $requiredSet2Count = 5;
    }
    else
    {
        $requiredSet2Count = $set2Count;
        if($requiredSet1Count > = (10 - $set2Count))
        {
            $requiredSet1Count = (10 - $set2Count);
        }
        else
        {
            $requiredSet1Count = $set1Count;
        }
    }
}
else
{
    .....// I gave up by the time I reached here....
}

在上面的代码中$set1Count$set2Count 是两个集合/数组中的实际结果计数。 $requiredSet1Count$requiredSet2Count 是我需要的动态计数,它将告诉我从每个集合中提取多少元素。

非常感谢任何帮助!

【问题讨论】:

    标签: php arrays algorithm dataset data-extraction


    【解决方案1】:

    我不知道没有 if 的变体。让我们尝试在每种情况下使用一个

    function requiredSet($set1count, $set2count) {
    // Both arrays together contain less than 10 items
        if ($set1count + $set2count <= 10) { 
            $requiredSet1Count  = $set1count;  $requiredSet2Count = $set2count;
        }
    // 1st less than 5 elements
        elseif ($set1count < 5) {
            $requiredSet1Count  = $set1count;
            $requiredSet2Count  = $set2count + $set1count > 10 ? 10 - $set1count : $set2count;
        }
    // 2nd - less than 5 elements
        elseif ($set2count < 5) {
            $requiredSet2Count  = $set2count;
            $requiredSet1Count  = $set1count + $set2count > 10 ? 10 - $set2count : $set1count;
        }
    // Just take 5 elements in each
        else $requiredSet1Count = $requiredSet2Count = 5;
    
        return array($requiredSet1Count, $requiredSet2Count);
    }
    
    echo '<pre>';
    var_export(requiredSet(1,2)); echo '<br>';
    var_export(requiredSet(2,5)); echo '<br>';
    var_export(requiredSet(2,7)); echo '<br>';
    var_export(requiredSet(2,13)); echo '<br>';
    var_export(requiredSet(13,11)); echo '<br>';
    

    结果

    array ( 0 => 1, 1 => 2)
    array ( 0 => 2, 1 => 5)
    array ( 0 => 2, 1 => 7)
    array ( 0 => 2, 1 => 8)
    array ( 0 => 5, 1 => 5)
    

    【讨论】:

    • 太完美了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2018-04-24
    相关资源
    最近更新 更多