CourseWorkKnapsack/classes/KnapsackSolver.cs

55 lines
1.4 KiB
C#
Raw Normal View History

2024-05-20 02:52:44 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectKnapsack.classes.KnapsackParameters;
namespace ProjectKnapsack.classes;
public class KnapsackSolver
{
private List<Item> items;
private int capacity;
private double currentWeight;
private double currentValue;
private int currentIndex;
public KnapsackSolver(KnapsackParameters parameters)
{
items = parameters.Items.OrderByDescending(i => i.Value / i.Weight).ToList();
capacity = parameters.Capacity;
currentWeight = 0;
currentValue = 0;
currentIndex = 0;
}
public KnapsackState SaveState()
{
return new KnapsackState(items, currentWeight, currentValue, currentIndex,capacity);
}
public void RestoreState(KnapsackState state)
{
items = new List<Item>(state.Items);
currentWeight = state.CurrentWeight;
currentValue = state.CurrentValue;
currentIndex = state.CurrentIndex;
}
public bool Step()
{
if (currentIndex >= items.Count)
return false;
Item item = items[currentIndex];
if (currentWeight + item.Weight <= capacity)
{
currentWeight += item.Weight;
currentValue += item.Value;
}
currentIndex++;
return true;
}
}