如何定义一个方程来根据权重计算对象(餐厅)的排名
How to define an equation to calculate rank of object (restaurant) based on weights
我有一系列餐厅,我需要根据这些规则计算每家餐厅的排名:
- 与我的距离(公里)
(weight=30)
- 赞
(weight=10)
$restaurants = [
{name: "KFC", distance: 17, likes: 3},
{name: "Macdonalds", distance: 2, likes: 9},
{name: "Pizza Hut", distance: 9, likes: 12},
{name: "Burger King", distance: 14, likes: 17},
];
排名越高意味着这家餐厅离我越近,并且根据方程获得更多的赞。
方程应该是什么?
这是您的问题的一种可能解决方案。我们使用权重数组,其键与 restaurants 数组中的键匹配,值如您的问题所示。请注意,对于距离,我们使用负值,因为您希望距离较近的餐厅(距离值越小)排名越高。然后我们可以根据每个权重的评分总和对餐厅数组进行排序:
function get_rating($restaurant, $weights) {
$rating = 0;
foreach ($weights as $factor => $weight) {
$rating += $weight * $restaurant[$factor];
}
return $rating;
}
$weights = array('distance' => -30, 'likes' => 10);
usort($restaurants, function ($a, $b) use ($weights) {
return get_rating($b, $weights) - get_rating($a, $weights);
});
print_r($restaurants);
输出:
Array
(
[0] => Array
(
[name] => Macdonalds
[distance] => 2
[likes] => 9
)
[1] => Array
(
[name] => Pizza Hut
[distance] => 9
[likes] => 12
)
[2] => Array
(
[name] => Burger King
[distance] => 14
[likes] => 17
)
[3] => Array
(
[name] => KFC
[distance] => 17
[likes] => 3
)
)
请注意,您问题中的 $restaurants
变量不是有效的 PHP 结构;我假设你有一个关联数组。
我有一系列餐厅,我需要根据这些规则计算每家餐厅的排名:
- 与我的距离(公里)
(weight=30)
- 赞
(weight=10)
$restaurants = [
{name: "KFC", distance: 17, likes: 3},
{name: "Macdonalds", distance: 2, likes: 9},
{name: "Pizza Hut", distance: 9, likes: 12},
{name: "Burger King", distance: 14, likes: 17},
];
排名越高意味着这家餐厅离我越近,并且根据方程获得更多的赞。
方程应该是什么?
这是您的问题的一种可能解决方案。我们使用权重数组,其键与 restaurants 数组中的键匹配,值如您的问题所示。请注意,对于距离,我们使用负值,因为您希望距离较近的餐厅(距离值越小)排名越高。然后我们可以根据每个权重的评分总和对餐厅数组进行排序:
function get_rating($restaurant, $weights) {
$rating = 0;
foreach ($weights as $factor => $weight) {
$rating += $weight * $restaurant[$factor];
}
return $rating;
}
$weights = array('distance' => -30, 'likes' => 10);
usort($restaurants, function ($a, $b) use ($weights) {
return get_rating($b, $weights) - get_rating($a, $weights);
});
print_r($restaurants);
输出:
Array
(
[0] => Array
(
[name] => Macdonalds
[distance] => 2
[likes] => 9
)
[1] => Array
(
[name] => Pizza Hut
[distance] => 9
[likes] => 12
)
[2] => Array
(
[name] => Burger King
[distance] => 14
[likes] => 17
)
[3] => Array
(
[name] => KFC
[distance] => 17
[likes] => 3
)
)
请注意,您问题中的 $restaurants
变量不是有效的 PHP 结构;我假设你有一个关联数组。