在 3d 数组的每个子集中找到最优选的元素,而无需选择两次值

问题描述 投票:0回答:1

我在弄清楚如何返回最佳的独特匹配,同时分配尽可能多的匹配时遇到一些困难。

场景:每个孩子都有一份最喜欢的水果清单,并附有个人得分。每种水果我们只有一个,所以我们想把它给最喜欢的孩子。如果有人得分较高,可以没有水果,但我们仍然希望尽可能多地赠送水果。

预期结果是:

0 = [1] Apple
1 = [0] Mango 
2 = [0] Banana
3 = null

这是我的输入数组:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => Banana
                    [score] => 80.2
                )
            [1] => Array
                (
                    [name] => Apple
                    [score] => 40
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [name] => Mango
                    [score] => 70
                )
            [1] => Array
                (
                    [name] => Banana
                    [score] => 40
                )
        )
    [2] => Array
        (
            [0] => Array
                (
                    [name] => Banana
                    [score] => 90
                )
            [1] => Array
                (
                    [name] => Orange
                    [score] => 20
                )
        )
    [3] => Array
        (
            [0] => Array
                (
                    [name] => Mango
                    [score] => 60
                )
        )
)
php arrays sorting multidimensional-array bucket
1个回答
1
投票

我的方法首先将您的输入展平为一个简单的二维数组,允许所有行按

score
排序,同时保留
fruit
childid
数据。排序后,所有行都会被迭代(而不是进行迭代的全数组搜索),并且仅根据要求为每个子项存储最喜欢的水果(如果可用)。

OP的输入:

$input=[
           [['name'=>'Banana','score'=>80.2],['name'=>'Apple','score'=>40]],
           [['name'=>'Mango','score'=>70],['name'=>'Banana','score'=>40]],
           [['name'=>'Banana','score'=>90],['name'=>'Orange','score'=>20]],
           [['name'=>'Mango','score'=>60]]
       ];

方法:

$result=array_fill_keys(array_keys($input),null);  // list all child ids and default to null

// flatten input array for simple sorting and iteration
foreach($input as $i=>$subarrays){
    foreach($subarrays as $a){
        $restructured[]=['score'=>$a['score'],'fruit'=>$a['name'],'childid'=>$i];
    }
}
rsort($restructured);  // will sort the array by score DESC

foreach($restructured as $a){
    if(is_null($result[$a['childid']]) && !in_array($a['fruit'],$result)){
        // only "fruitless" children wanting what is available
        $result[$a['childid']]=$a['fruit']; 
    }
}

var_export($result);

输出:

array (
  0 => 'Apple',
  1 => 'Mango',
  2 => 'Banana',
  3 => NULL,
)
© www.soinside.com 2019 - 2024. All rights reserved.