Naive Knapsack Solver Algorithm

The Naive Knapsack Solver Algorithm is a straightforward and simple approach to solving the Knapsack problem, a classic optimization problem in computer science and mathematics. The Knapsack problem involves determining the most valuable combination of items to include in a knapsack, given a collection of items, each with its own value and weight, and a limited carrying capacity of the knapsack. The Naive Knapsack Solver Algorithm, as the name suggests, is a naive or brute-force method to find the optimal solution, involving the generation of all possible combinations of items and calculating their total values and weights to find the combination that maximizes value without exceeding the weight capacity of the knapsack. The algorithm begins by generating all possible subsets of items from the given collection, which can be done using a recursive method or an iterative one, such as looping through all binary representations of the item set. For each subset, the algorithm calculates the total weight and value, and compares them against the current best solution. If the total weight of the subset is within the knapsack's capacity and its value is greater than the current best solution, the algorithm updates the best solution to the current subset. This process is repeated for all possible subsets, and the algorithm returns the best solution found, which is the optimal solution for the problem. While the Naive Knapsack Solver Algorithm is simple to understand and implement, it suffers from exponential time complexity due to the generation of all possible subsets, making it inefficient for large-scale problems. More advanced methods, such as dynamic programming or greedy algorithms, can be employed to solve the Knapsack problem more efficiently.
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();
        }
    }
}

LANGUAGE:

DARK MODE: