Курсовая

This commit is contained in:
asakky 2024-05-20 02:52:44 +04:00
parent 8cc7e4f9a7
commit 6f18d1f7cc
18 changed files with 1193 additions and 0 deletions

14
Program.cs Normal file
View File

@ -0,0 +1,14 @@
using ProjectKnapsack.forms;
namespace ProjectKnapsack;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}

11
ProjectKnapsack.csproj Normal file
View File

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

25
ProjectKnapsack.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectKnapsack", "ProjectKnapsack.csproj", "{FC821C97-5F32-4427-A519-5A22A0D288E9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FC821C97-5F32-4427-A519-5A22A0D288E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FC821C97-5F32-4427-A519-5A22A0D288E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FC821C97-5F32-4427-A519-5A22A0D288E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FC821C97-5F32-4427-A519-5A22A0D288E9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {35A1E4E6-69DB-4A8A-A4D5-C60563ECC2C9}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectKnapsack.classes;
public class KnapsackManager
{
private KnapsackSolver solver;
private Storage storage;
public KnapsackManager(KnapsackParameters parameters)
{
solver = new KnapsackSolver(parameters);
storage = new Storage();
storage.AddState(solver.SaveState());
}
public void Execute()
{
while (solver.Step())
{
storage.AddState(solver.SaveState());
}
}
public Storage Storage => storage;
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectKnapsack.classes;
public class KnapsackParameters
{
public int Capacity { get; set; }
public List<Item> Items { get; set; }
public class Item
{
public string Name { get; set; }
public int Weight { get; set; }
public int Value { get; set; }
}
}

54
classes/KnapsackSolver.cs Normal file
View File

@ -0,0 +1,54 @@
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;
}
}

26
classes/KnapsackStatus.cs Normal file
View File

@ -0,0 +1,26 @@
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 KnapsackState
{
public List<Item> Items { get; }
public double CurrentWeight { get; }
public double CurrentValue { get; }
public int CurrentIndex { get; }
public int Capacity { get; set; } // Добавляем свойство для хранения вместимости рюкзака
public KnapsackState(List<Item> items, double currentWeight, double currentValue, int currentIndex, int capacity)
{
Items = new List<Item>(items);
CurrentWeight = currentWeight;
CurrentValue = currentValue;
CurrentIndex = currentIndex;
Capacity = capacity; // Инициализируем вместимость рюкзака
}
}

View File

@ -0,0 +1,61 @@
using ProjectKnapsack.forms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectKnapsack.classes.KnapsackParameters;
namespace ProjectKnapsack.classes;
public class KnapsackVisualizer
{
public void Visualize(List<Item> items, int capacity, MainForm form)
{
PictureBox? pictureBox = form.Controls["pictureBox1"] as PictureBox;// получаем ссылку на PictureBox на форме
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
// Отрисовка рюкзака
int knapsackWidth = 100;
int knapsackHeight = 200;
int knapsackX = 50;
int knapsackY = pictureBox.Height / 2 - knapsackHeight / 2;
graphics.FillRectangle(Brushes.LightGray, knapsackX, knapsackY, knapsackWidth, knapsackHeight);
graphics.DrawRectangle(Pens.Black, knapsackX, knapsackY, knapsackWidth, knapsackHeight);
// Добавление текста "Капацитет" рядом с рюкзаком
string capacityText = "Capacity: " + capacity;
graphics.DrawString(capacityText, SystemFonts.DefaultFont, Brushes.Black, knapsackX + knapsackWidth + 10, knapsackY);
// Отрисовка выбранных предметов
int startX = 200;
int startY = 50;
int spacingX = 150;
foreach (var item in items)
{
int itemWidth = item.Weight;
int itemHeight = item.Value;
int itemX = startX + items.IndexOf(item) * spacingX;
int itemY = startY;
// Отрисовка прямоугольника, представляющего предмет
graphics.FillRectangle(Brushes.LightBlue, itemX, itemY, itemWidth, itemHeight);
graphics.DrawRectangle(Pens.Black, itemX, itemY, itemWidth, itemHeight);
// Добавление текста с именем предмета
string itemName = item.Name;
graphics.DrawString(itemName, SystemFonts.DefaultFont, Brushes.Black, itemX, itemY + itemHeight + 5);
}
}
pictureBox.Image = bitmap; // Отображение изображения на PictureBox
}
}

51
classes/Storage.cs Normal file
View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.IO;
namespace ProjectKnapsack.classes;
public class Storage
{
private List<KnapsackState> states;
private int currentPosition;
public Storage()
{
states = new List<KnapsackState>();
currentPosition = 0;
}
public void AddState(KnapsackState state)
{
states.Add(state);
}
public KnapsackState GetState(int index)
{
return states[index];
}
public int StateCount => states.Count;
public void SaveToFile(string filename)
{
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(states, options);
File.WriteAllText(filename, json);
}
public void LoadFromFile(string filename)
{
var json = File.ReadAllText(filename);
states = JsonSerializer.Deserialize<List<KnapsackState>>(json);
}
public void Reset()
{
currentPosition = 0;
}
}

93
forms/InformationForm.Designer.cs generated Normal file
View File

@ -0,0 +1,93 @@
namespace ProjectKnapsack.forms
{
partial class InformationForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private Button buttonCloseInfoForm;
private RichTextBox richTextBox1;
private RichTextBox richTextBox2;
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InformationForm));
buttonCloseInfoForm = new Button();
richTextBox1 = new RichTextBox();
richTextBox2 = new RichTextBox();
SuspendLayout();
//
// buttonCloseInfoForm
//
buttonCloseInfoForm.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCloseInfoForm.Location = new Point(672, 332);
buttonCloseInfoForm.Name = "buttonCloseInfoForm";
buttonCloseInfoForm.Size = new Size(92, 26);
buttonCloseInfoForm.TabIndex = 1;
buttonCloseInfoForm.Text = "Закрыть";
buttonCloseInfoForm.UseVisualStyleBackColor = true;
buttonCloseInfoForm.Click += buttonCloseInfoForm_Click;
//
// richTextBox1
//
richTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
richTextBox1.BackColor = SystemColors.ControlLightLight;
richTextBox1.Font = new Font("Times New Roman", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
richTextBox1.Location = new Point(12, 63);
richTextBox1.Name = "richTextBox1";
richTextBox1.ReadOnly = true;
richTextBox1.Size = new Size(752, 70);
richTextBox1.TabIndex = 2;
richTextBox1.Text = resources.GetString("richTextBox1.Text");
//
// richTextBox2
//
richTextBox2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
richTextBox2.BackColor = SystemColors.ControlLightLight;
richTextBox2.Font = new Font("Times New Roman", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
richTextBox2.Location = new Point(12, 178);
richTextBox2.Name = "richTextBox2";
richTextBox2.ReadOnly = true;
richTextBox2.Size = new Size(752, 87);
richTextBox2.TabIndex = 3;
richTextBox2.Text = resources.GetString("richTextBox2.Text");
//
// InformationForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.SandyBrown;
ClientSize = new Size(776, 370);
Controls.Add(richTextBox2);
Controls.Add(richTextBox1);
Controls.Add(buttonCloseInfoForm);
Name = "InformationForm";
Text = "InformationForm";
ResumeLayout(false);
}
#endregion
}
}

23
forms/InformationForm.cs Normal file
View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectKnapsack.forms;
public partial class InformationForm : Form
{
public InformationForm()
{
InitializeComponent();
}
private void buttonCloseInfoForm_Click(object sender, EventArgs e)
{
Close();
}
}

126
forms/InformationForm.resx Normal file
View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="richTextBox1.Text" xml:space="preserve">
<value>Задача о рюкзаке (англ. Knapsack problem) — дано предметов, предмет имеет массу и стоимость . Необходимо выбрать из этих предметов такой набор, чтобы суммарная масса не превосходила заданной величины (вместимость рюкзака), а суммарная стоимость была максимальна.</value>
</data>
<data name="richTextBox2.Text" xml:space="preserve">
<value>Жадный алгоритм для задачи о рюкзаке состоит в следующем (считаем, что все предметы помещаются в рюкзак): Выбрать максимально дорогой предмет, стоимости Cmax . Упорядочить предметы по «удельной стоимости» (стоимости деленной на вес), и набивать рюкзак наиболее «удельно дорогими» предметами, пока они влезают.</value>
</data>
</root>

134
forms/MainForm.Designer.cs generated Normal file
View File

@ -0,0 +1,134 @@
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectKnapsack.forms
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
///
private System.Windows.Forms.Button startButton;
private MenuStrip menuStrip;
private ToolStripMenuItem fileMenuItem;
private ToolStripMenuItem saveMenuItem;
private ToolStripMenuItem loadMenuItem;
private ToolStripMenuItem helpMenuItem;
private ToolStripMenuItem aboutMenuItem;
private void InitializeComponent()
{
startButton = new System.Windows.Forms.Button();
menuStrip = new MenuStrip();
fileMenuItem = new ToolStripMenuItem();
saveMenuItem = new ToolStripMenuItem();
loadMenuItem = new ToolStripMenuItem();
helpMenuItem = new ToolStripMenuItem();
aboutMenuItem = new ToolStripMenuItem();
pictureBox1 = new PictureBox();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
SuspendLayout();
//
// startButton
//
startButton.Location = new Point(50, 500);
startButton.Name = "startButton";
startButton.Size = new Size(100, 30);
startButton.TabIndex = 0;
startButton.Text = "Start";
startButton.Click += startButton_Click;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { fileMenuItem, helpMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 24);
menuStrip.TabIndex = 2;
//
// fileMenuItem
//
fileMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveMenuItem, loadMenuItem });
fileMenuItem.Name = "fileMenuItem";
fileMenuItem.Size = new Size(37, 20);
fileMenuItem.Text = "File";
//
// saveMenuItem
//
saveMenuItem.Name = "saveMenuItem";
saveMenuItem.Size = new Size(100, 22);
saveMenuItem.Text = "Save";
saveMenuItem.Click += saveMenuItem_Click;
//
// loadMenuItem
//
loadMenuItem.Name = "loadMenuItem";
loadMenuItem.Size = new Size(100, 22);
loadMenuItem.Text = "Load";
loadMenuItem.Click += loadMenuItem_Click;
//
// helpMenuItem
//
helpMenuItem.DropDownItems.AddRange(new ToolStripItem[] { aboutMenuItem });
helpMenuItem.Name = "helpMenuItem";
helpMenuItem.Size = new Size(44, 20);
helpMenuItem.Text = "Help";
//
// aboutMenuItem
//
aboutMenuItem.Name = "aboutMenuItem";
aboutMenuItem.Size = new Size(107, 22);
aboutMenuItem.Text = "About";
aboutMenuItem.Click += aboutMenuItem_Click;
//
// pictureBox1
//
pictureBox1.Location = new Point(0, 27);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(800, 467);
pictureBox1.TabIndex = 3;
pictureBox1.TabStop = false;
//
// MainForm
//
ClientSize = new Size(800, 600);
Controls.Add(pictureBox1);
Controls.Add(startButton);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "MainForm";
Text = "Knapsack Problem Visualizer";
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBox1;
}
}

100
forms/MainForm.cs Normal file
View File

@ -0,0 +1,100 @@
using ProjectKnapsack.classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectKnapsack.forms;
public partial class MainForm : Form
{
private KnapsackVisualizer visualization;
private KnapsackManager manager;
private Storage storage;
private int currentStep;
public MainForm()
{
InitializeComponent();
visualization = new KnapsackVisualizer();
}
private void startButton_Click(object sender, EventArgs e)
{
var parametersForm = new ParametersForm();
if (parametersForm.ShowDialog() == DialogResult.OK)
{
var parameters = parametersForm.Parameters;
if (parameters != null) // Добавьте проверку на null перед использованием параметров
{
manager = new KnapsackManager(parameters);
manager.Execute();
storage = manager.Storage;
currentStep = 0;
DisplayCurrentState();
}
else
{
MessageBox.Show("Parameters are null.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void DisplayCurrentState()
{
if (storage != null && visualization != null)
{
var state = storage.GetState(currentStep);
if (state != null)
{
visualization.Visualize(state.Items, state.Capacity, this);
}
else
{
MessageBox.Show("State is null.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void saveMenuItem_Click(object sender, EventArgs e)
{
if (storage != null)
{
using (var saveFileDialog = new SaveFileDialog())
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
storage.SaveToFile(saveFileDialog.FileName);
}
}
}
else
{
MessageBox.Show("No data to save.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void loadMenuItem_Click(object sender, EventArgs e)
{
using (var openFileDialog = new OpenFileDialog())
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
storage = new Storage();
storage.LoadFromFile(openFileDialog.FileName);
currentStep = 0;
DisplayCurrentState();
}
}
}
private void aboutMenuItem_Click(object sender, EventArgs e)
{
InformationForm informationForm = new InformationForm();
informationForm.Show();
}
}

123
forms/MainForm.resx Normal file
View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

116
forms/ParametersForm.Designer.cs generated Normal file
View File

@ -0,0 +1,116 @@
namespace ProjectKnapsack.forms
{
partial class ParametersForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private Label capacityLabel;
private NumericUpDown capacityNumericUpDown;
private Label itemsLabel;
private DataGridView itemsDataGridView;
private Button okButton;
private Button cancelButton;
private void InitializeComponent()
{
capacityLabel = new Label();
capacityNumericUpDown = new NumericUpDown();
itemsLabel = new Label();
itemsDataGridView = new DataGridView();
okButton = new Button();
cancelButton = new Button();
SuspendLayout();
// Capacity Label
capacityLabel.AutoSize = true;
capacityLabel.Location = new System.Drawing.Point(12, 9);
capacityLabel.Name = "capacityLabel";
capacityLabel.Size = new System.Drawing.Size(80, 13);
capacityLabel.Text = "Knapsack Capacity:";
// Capacity NumericUpDown
capacityNumericUpDown.Location = new System.Drawing.Point(150, 7);
capacityNumericUpDown.Minimum = 1;
capacityNumericUpDown.Maximum = 1000;
capacityNumericUpDown.Name = "capacityNumericUpDown";
capacityNumericUpDown.Size = new System.Drawing.Size(120, 20);
// Items Label
itemsLabel.AutoSize = true;
itemsLabel.Location = new System.Drawing.Point(12, 40);
itemsLabel.Name = "itemsLabel";
itemsLabel.Size = new System.Drawing.Size(80, 13);
itemsLabel.Text = "Items:";
// Items DataGridView
itemsDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
itemsDataGridView.Columns.Add("Name", "Name");
itemsDataGridView.Columns.Add("Weight", "Weight");
itemsDataGridView.Columns.Add("Value", "Value");
itemsDataGridView.Location = new System.Drawing.Point(15, 60);
itemsDataGridView.Name = "itemsDataGridView";
itemsDataGridView.Size = new System.Drawing.Size(360, 200);
itemsDataGridView.AllowUserToAddRows = true;
itemsDataGridView.AllowUserToDeleteRows = true;
// OK Button
okButton.Location = new System.Drawing.Point(219, 270);
okButton.Name = "okButton";
okButton.Size = new System.Drawing.Size(75, 23);
okButton.Text = "OK";
okButton.UseVisualStyleBackColor = true;
okButton.Click += new EventHandler(okButton_Click);
// Cancel Button
cancelButton.Location = new System.Drawing.Point(300, 270);
cancelButton.Name = "cancelButton";
cancelButton.Size = new System.Drawing.Size(75, 23);
cancelButton.Text = "Cancel";
cancelButton.UseVisualStyleBackColor = true;
cancelButton.Click += new EventHandler(cancelButton_Click);
// ParametersForm
ClientSize = new System.Drawing.Size(384, 311);
Controls.Add(capacityLabel);
Controls.Add(capacityNumericUpDown);
Controls.Add(itemsLabel);
Controls.Add(itemsDataGridView);
Controls.Add(okButton);
Controls.Add(cancelButton);
Name = "ParametersForm";
Text = "Input Parameters";
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
MinimizeBox = false;
StartPosition = FormStartPosition.CenterParent;
((System.ComponentModel.ISupportInitialize)(capacityNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(itemsDataGridView)).EndInit();
}
}
#endregion
}

64
forms/ParametersForm.cs Normal file
View File

@ -0,0 +1,64 @@
using ProjectKnapsack.classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ProjectKnapsack.classes.KnapsackParameters;
namespace ProjectKnapsack.forms;
public partial class ParametersForm : Form
{
public ParametersForm()
{
InitializeComponent();
}
private void okButton_Click(object sender, EventArgs e)
{
// После ввода всех предметов закрываем форму и передаем список предметов в основную форму
this.DialogResult = DialogResult.OK;
this.Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void addItemButton_Click(object sender, EventArgs e)
{
itemsDataGridView.Rows.Add("", 0, 0); // Добавляем новую строку в DataGridView
}
public KnapsackParameters Parameters
{
get
{
var items = new List<Item>();
foreach (DataGridViewRow row in itemsDataGridView.Rows)
{
if (row.IsNewRow) continue;
var item = new Item
{
Name = row.Cells["Name"].Value?.ToString(),
Weight = Convert.ToInt32(row.Cells["Weight"].Value),
Value = Convert.ToInt32(row.Cells["Value"].Value)
};
items.Add(item);
}
return new KnapsackParameters
{
Capacity = (int)capacityNumericUpDown.Value,
Items = items
};
}
}
}

120
forms/ParametersForm.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>