Aradığınız şey sırt çantası problemi için bir çözümdür. Bunu hızlı yapmanın bilinen bir yolu yoktur. Böyle en fazla maxCount
öğeleri seçmek için dinamik bir çözüm (https://en.wikipedia.org/wiki/Knapsack_problem#0.2F1_knapsack_problem) değiştirebilirsiniz:
public static List<Item> BestCombination(List<Item> items, int maxPrice, int maxCount)
{
var scores = new int[items.Count + 1, maxPrice + 1, maxCount + 1];
for (int i = 1; i <= items.Count; i++)
{
var item = items[i - 1];
for (int count = 1; count <= Math.Min(maxCount, i); count++)
{
for (int price = 0; price <= maxPrice; price++)
{
if (item.Price > price)
scores[i, price, count] = scores[i - 1, price, count];
else
scores[i, price, count] = Math.Max(
scores[i - 1, price, count],
scores[i - 1, price - item.Price, count - 1] + item.Score);
}
}
}
var choosen = new List<Item>();
int j = maxPrice;
int k = maxCount;
for (int i = items.Count; i > 0; i--)
{
var item = items[i - 1];
if (scores[i, j, k] != scores[i - 1, j, k])
{
choosen.Add(item);
j -= item.Price;
k--;
}
}
return choosen;
}
aklınızda tutun
maxCount
nesneleri
<= maxCount
nesneleri seçmek yerine size daha düşük toplam puan verebilir exaclty seçmek. Örneğin [(100, 10), (200,20), (300,30), (500,80)], maxPrice = 500 ve maxCount = 2 öğeleri için bu yöntem sadece döner (500,80). Eğer, sen başlatabilir dizi şöyle [(300,30), (200,20)] geri dönmek isterseniz:
for (int i = 0; i <= items.Count; i++)
{
for (int price = 0; price <= maxPrice; price++)
{
for (int count = 1; count <= maxCount; count++)
{
scores[i, price, count] = int.MinValue;
}
}
}
yılında scores[, , count]
count
puanları (veya MinValue
) toplamından oluşmasıdır emin olmak için. Bununla birlikte, tam olarak maxCount
'u seçmenin bir yolu yoksa, başka bir sayıda öğe döndürebilir.
Linq'i kullanarak incelediniz mi? – Captain0
Bazı sebeplerden dolayı bu durum akla https://simple.wikipedia.org/wiki/Travelling_salesman_problem –
@DanielvanHeerden: Bu aslında sırt çantası problemine benziyor. Muhtemelen TSP akla gelir çünkü hem onun hem de sırt çantasının problemi optimal durum için bilinen bir polinom zaman çözümüne sahip değildir ve dahası, eğer * bir tanesi * yaparsa, o zaman * diğer * biri de yapar. Hızla optimal bir algoritmaya sahip olmadığına inanılmaktadır. –