public void Solve(IPlotter plotter)
        {
            // Given an array of N items, where each item is represented by a tuple (weight, value)
            // Given a knapsack weight capacity
            // Find the maximum total value in the knapsack without exceeding its capacity
            // Items cannot be fractioned

            ReadOnlySpan <Item> items = stackalloc Item[]
            {
                new Item {
                    Weight = 1, Value = 1
                },
                new Item {
                    Weight = 2, Value = 6
                },
                new Item {
                    Weight = 3, Value = 10
                },
                new Item {
                    Weight = 5, Value = 16
                }
            };

            var capacity = 7;

            var solution = _strategy.Solve(items, capacity);

            plotter.PlotValues(nameof(items), items);
            plotter.PlotValue(nameof(capacity), capacity);
            plotter.PlotValues(nameof(solution), (ReadOnlySpan <Item>)solution);
            plotter.PlotValue("total", solution.Sum(i => i.Value));
        }
    }
Beispiel #2
0
 public static void PlotValues <T>(this IPlotter plotter, string name, ReadOnlySpan <T> values)
 {
     plotter.PlotLine($"{name}:");
     for (var i = 0; i < values.Length; i++)
     {
         plotter.PlotValue($"  {i}", values[i]);
     }
 }
Beispiel #3
0
        public void Solve(IPlotter plotter)
        {
            // Given an array of numbers that represent the values of each coin
            // Given an amount
            // Find the minimum number of coins that are needed to make that amount

            ReadOnlySpan <int> coins = stackalloc int[] { 1, 5, 10, 25, 50 };
            const int          value = 74;

            var solution = _strategy.Solve(coins, value);

            plotter.PlotValue(nameof(value), value);
            for (var i = 0; i < coins.Length; i++)
            {
                plotter.PlotLine($"{solution[i]} coin(s) of {coins[i]}");
            }
        }
    }