forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NaiveKnapsackSolver.cs
37 lines (33 loc) · 1.02 KB
/
NaiveKnapsackSolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
namespace Algorithms.Knapsack;
/// <summary>
/// Greedy heurictic solver.
/// </summary>
/// <typeparam name="T">Type of items in knapsack.</typeparam>
public class NaiveKnapsackSolver<T> : IHeuristicKnapsackSolver<T>
{
/// <summary>
/// TODO.
/// </summary>
/// <param name="items">TODO. 2.</param>
/// <param name="capacity">TODO. 3.</param>
/// <param name="weightSelector">TODO. 4.</param>
/// <param name="valueSelector">TODO. 5.</param>
/// <returns>TODO. 6.</returns>
public T[] Solve(T[] items, double capacity, Func<T, double> weightSelector, Func<T, double> valueSelector)
{
var weight = 0d;
var left = new List<T>();
foreach (var item in items)
{
var weightDelta = weightSelector(item);
if (weight + weightDelta <= capacity)
{
weight += weightDelta;
left.Add(item);
}
}
return left.ToArray();
}
}