diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..a1c34d8 --- /dev/null +++ b/Program.cs @@ -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()); + } +} \ No newline at end of file diff --git a/ProjectKnapsack.csproj b/ProjectKnapsack.csproj new file mode 100644 index 0000000..663fdb8 --- /dev/null +++ b/ProjectKnapsack.csproj @@ -0,0 +1,11 @@ + + + + WinExe + net8.0-windows + enable + true + enable + + + \ No newline at end of file diff --git a/ProjectKnapsack.sln b/ProjectKnapsack.sln new file mode 100644 index 0000000..3a4f165 --- /dev/null +++ b/ProjectKnapsack.sln @@ -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 diff --git a/classes/KnapsackManager.cs b/classes/KnapsackManager.cs new file mode 100644 index 0000000..fcfe5df --- /dev/null +++ b/classes/KnapsackManager.cs @@ -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; +} diff --git a/classes/KnapsackParameters.cs b/classes/KnapsackParameters.cs new file mode 100644 index 0000000..efc3d5b --- /dev/null +++ b/classes/KnapsackParameters.cs @@ -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 Items { get; set; } + + + public class Item + { + public string Name { get; set; } + public int Weight { get; set; } + public int Value { get; set; } + + } +} diff --git a/classes/KnapsackSolver.cs b/classes/KnapsackSolver.cs new file mode 100644 index 0000000..e512aa7 --- /dev/null +++ b/classes/KnapsackSolver.cs @@ -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 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(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; + } +} diff --git a/classes/KnapsackStatus.cs b/classes/KnapsackStatus.cs new file mode 100644 index 0000000..8b3418c --- /dev/null +++ b/classes/KnapsackStatus.cs @@ -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 Items { get; } + public double CurrentWeight { get; } + public double CurrentValue { get; } + public int CurrentIndex { get; } + public int Capacity { get; set; } // Добавляем свойство для хранения вместимости рюкзака + + public KnapsackState(List items, double currentWeight, double currentValue, int currentIndex, int capacity) + { + Items = new List(items); + CurrentWeight = currentWeight; + CurrentValue = currentValue; + CurrentIndex = currentIndex; + Capacity = capacity; // Инициализируем вместимость рюкзака + } +} diff --git a/classes/KnapsackVisualizer.cs b/classes/KnapsackVisualizer.cs new file mode 100644 index 0000000..ad3f87d --- /dev/null +++ b/classes/KnapsackVisualizer.cs @@ -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 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 + } + +} diff --git a/classes/Storage.cs b/classes/Storage.cs new file mode 100644 index 0000000..b4d7ce2 --- /dev/null +++ b/classes/Storage.cs @@ -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 states; + private int currentPosition; + + public Storage() + { + states = new List(); + 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>(json); + } + + public void Reset() + { + currentPosition = 0; + } +} diff --git a/forms/InformationForm.Designer.cs b/forms/InformationForm.Designer.cs new file mode 100644 index 0000000..5a82326 --- /dev/null +++ b/forms/InformationForm.Designer.cs @@ -0,0 +1,93 @@ +namespace ProjectKnapsack.forms +{ + partial class InformationForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + + 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 + } +} \ No newline at end of file diff --git a/forms/InformationForm.cs b/forms/InformationForm.cs new file mode 100644 index 0000000..4128584 --- /dev/null +++ b/forms/InformationForm.cs @@ -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(); + } +} diff --git a/forms/InformationForm.resx b/forms/InformationForm.resx new file mode 100644 index 0000000..6827651 --- /dev/null +++ b/forms/InformationForm.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Задача о рюкзаке (англ. Knapsack problem) — дано предметов, предмет имеет массу и стоимость . Необходимо выбрать из этих предметов такой набор, чтобы суммарная масса не превосходила заданной величины (вместимость рюкзака), а суммарная стоимость была максимальна. + + + Жадный алгоритм для задачи о рюкзаке состоит в следующем (считаем, что все предметы помещаются в рюкзак): Выбрать максимально дорогой предмет, стоимости Cmax . Упорядочить предметы по «удельной стоимости» (стоимости деленной на вес), и набивать рюкзак наиболее «удельно дорогими» предметами, пока они влезают. + + \ No newline at end of file diff --git a/forms/MainForm.Designer.cs b/forms/MainForm.Designer.cs new file mode 100644 index 0000000..7942360 --- /dev/null +++ b/forms/MainForm.Designer.cs @@ -0,0 +1,134 @@ +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace ProjectKnapsack.forms +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + /// + 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; + } +} \ No newline at end of file diff --git a/forms/MainForm.cs b/forms/MainForm.cs new file mode 100644 index 0000000..aacf969 --- /dev/null +++ b/forms/MainForm.cs @@ -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(); + } +} diff --git a/forms/MainForm.resx b/forms/MainForm.resx new file mode 100644 index 0000000..6c82d08 --- /dev/null +++ b/forms/MainForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/forms/ParametersForm.Designer.cs b/forms/ParametersForm.Designer.cs new file mode 100644 index 0000000..4dacac4 --- /dev/null +++ b/forms/ParametersForm.Designer.cs @@ -0,0 +1,116 @@ +namespace ProjectKnapsack.forms +{ + partial class ParametersForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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 +} diff --git a/forms/ParametersForm.cs b/forms/ParametersForm.cs new file mode 100644 index 0000000..f833466 --- /dev/null +++ b/forms/ParametersForm.cs @@ -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(); + 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 + }; + } + } +} diff --git a/forms/ParametersForm.resx b/forms/ParametersForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/forms/ParametersForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file