给出以下项目列表,预算B和项目类型列表(T1,T2,T3 ... TN),从每种类型中选择1个提供最大价值(最昂贵)而又不超出预算的项目
[
{
"id": "1",
"types": "T1",
"price": 1000,
},
{
"id": "2",
"types": "T2",
"price": 109292,
},
{
"id": "3",
"types": "T3",
"price": 7228,
},
{
"id": "4",
"types": "T4",
"price": 1000,
},
]
研究了背包问题,不确定是否是NP完全问题。
答案 0 :(得分:1)
只需使用filter
查找不超过预算的所有项目,然后按sort
降序排列并采用第一个元素:
const array = [{
"id": "1",
"types": "T1",
"price": 1000,
},
{
"id": "2",
"types": "T2",
"price": 109292,
},
{
"id": "3",
"types": "T3",
"price": 7228,
},
{
"id": "4",
"types": "T4",
"price": 1000,
},
];
const budget = 9000;
var budgetMatch = array.filter(({ price }) => price <= budget);
budgetMatch.sort(({ price: a}, { price: b}) => b - a);
var highestPrice = budgetMatch[0];
console.log(highestPrice);