Мне интересно мнение очень опытных программистов о том, какие улучшения необходимы для того, чтобы этот код прошел. Я не понимаю, почему это не удалось, и хотел бы расширить свои знания, получив отзывы экспертов.
Экзамен по программированию
Это экзамен< /strong>
Создайте приложение формы Windows, отвечающее следующим требованиям на C#.
Основная функция программы — сортировка строки с входными данными. от пользователя.
Пример ввода: befdac
Ожидаемый результат: abcdef
Пользовательский интерфейс будет содержать следующие четыре элемента:
Текстовое поле, позволяющее пользователю вводить строку. Элемент управления (
например, поле со списком), который выбирает стратегию. использовать для сортировки строки.
Кнопка, которая будет сортировать строку с использованием выбранной стратегии.
Метка, на которой будут отображаться выходные данные (отсортированная строка)
Целью задания является реализация ШАБЛОНОВ ДИЗАЙНА.
a. Шаблон стратегии: шаблон проектирования программного обеспечения, который позволяет выбирать поведение алгоритма во время выполнения. Шаблон стратегии будет использоваться для сортировки строк в двух разных реализациях. Вы можете выбрать два метода сортировки: пузырьковая сортировка, быстрая сортировка или сортировка слиянием.
b. Что касается логики и представления приложения, оно будет реализовано в шаблоне Модель-Представление-Контроллер, и вам не разрешено использовать для этого структуру.
Обязательно соблюдайте соответствующие правила. практики разработки и обеспечить наличие всех проверок. Напишите модульные тесты для отдельных компонентов вашего кода, чтобы получить преимущество.
Мой код
Интерфейс
public interface ISortStrategy
{
string Sort(string input);
}
Контроллер
namespace YouSourceCodingExam.Controller
{
public class SortController
{
private readonly SortModel _model;
private ISortStrategy _strategy;
public SortController(SortModel model)
{
_model = model;
}
public void SetSortStrategy(ISortStrategy strategy)
{
_strategy = strategy;
}
public void Sort()
{
if (_strategy != null)
{
_model.Sorted = _strategy.Sort(_model.Input);
}
}
public void UpdateModel(string input)
{
_model.Input = input;
}
public string GetSortedString()
{
return _model.Sorted;
}
}
}
Модель
public class SortModel
{
public string Input { get; set; }
public string Sorted { get; set; }
}
Конкретные стратегии
public class BubbleSortStrategy : ISortStrategy
{
//BUBBLE SORT STRATEGY
public string Sort(string input)
{
//Repeatedly steps through the list, compares elements, and swaps them if they are
//in the wrong order.This process is repeated until the list is sorted.
if (string.IsNullOrEmpty(input)) return input;
char[] str = input.ToCharArray();
for (int i = 0; i < str.Length - 1; i++)
{
for (int j = 0; j < str.Length - i - 1; j++)
{
if (str[j] > str[j + 1])
{
// Swap str[j] and str[j+1]
char t = str[j];
str[j] = str[j + 1];
str[j + 1] = t;
}
}
}
return new string(str);
//OR USING LINQ
var sortedChars = input.OrderBy(c => c);
return new string(sortedChars.ToArray());
}
}
public class QuickSortStrategy : ISortStrategy
{
//QUICK SORT STRATEGY
public string Sort(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input), "Input cannot be null.");
if (input.Length == 0)
return input;
char[] str = input.ToCharArray();
QSort(str, 0, str.Length - 1);
return new string(str);
}
private void QSort(char[] str, int l, int h)
{
if (l < h)
{
int pi = Split(str, l, h);
//Iterate repetitively before spllitting
QSort(str, l, pi - 1);
QSort(str, pi + 1, h);
}
}
//Method to split or partition the string array
private int Split(char[] str, int l, int h)
{
char p = str[h];
int i = (l - 1); //smaller element
for (int j = l; j < h; j++)
{
//if current is smaller than or equal to p
if (str[j] < p)
{
i++;
char t = str;
str = str[j];
str[j] = t;
}
}
char s = str[i + 1];
str[i + 1] = str[h];
str[h] = s;
return i + 1;
}
}
Просмотр
public partial class MainForm : Form
{
private readonly SortModel _model;
private readonly SortController _controller;
public MainForm()
{
InitializeComponent();
_model = new SortModel();
_controller = new SortController(_model);
// Populate ComboBox with sorting strategies
comboBoxSortStrategy.Items.Add("Bubble Sort");
comboBoxSortStrategy.Items.Add("Quick Sort");
comboBoxSortStrategy.SelectedIndex = 0;
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void buttonSort_Click(object sender, EventArgs e)
{
string input = textBoxInput.Text;
// Validate the input
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Input string cannot be null or empty.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_controller.UpdateModel(input);
// Set the sorting strategy based on ComboBox selection
ISortStrategy strategy;
string selectedStrategy = comboBoxSortStrategy.SelectedItem.ToString();
if (selectedStrategy == "Bubble Sort")
{
strategy = new BubbleSortStrategy();
}
else if (selectedStrategy == "Quick Sort")
{
strategy = new QuickSortStrategy();
}
else
{
throw new InvalidOperationException("Invalid sorting strategy selected");
}
_controller.SetSortStrategy(strategy);
_controller.Sort();
labelOutput.Text = _controller.GetSortedString();
}
private void comboBoxSortStrategy_SelectedIndexChanged(object sender, EventArgs e)
{
labelOutput.Text = "";
textBoxInput.Text = "";
}
}
Модульное тестирование
namespace YouSourceCodingExamTest
{
[TestFixture]
public class SortStrategyTests
{
//Sorting Test
[Test]
public void BubbleSort_SortsCorrectly()
{
// Arrange
var strategy = new BubbleSortStrategy();
string input = "befdac";
string expected = "abcdef";
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_SortsCorrectly()
{
// Arrange
var strategy = new QuickSortStrategy();
string input = "befdac";
string expected = "abcdef";
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
//Empty String Test
[Test]
public void BubbleSort_EmptyString_ReturnsEmpty()
{
var strategy = new BubbleSortStrategy();
string input = "";
string expected = "";
string result = strategy.Sort(input);
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_EmptyString_ReturnsEmpty()
{
var strategy = new QuickSortStrategy();
string input = "";
string expected = "";
string result = strategy.Sort(input);
Assert.AreEqual(expected, result);
}
//Validation Test
[Test]
public void BubbleSort_NullString_ReturnsNull()
{
// Arrange
var strategy = new BubbleSortStrategy();
string input = null;
string expected = null;
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_NullString_ThrowsArgumentNullException()
{
// Arrange
var strategy = new QuickSortStrategy();
string input = null;
// Act & Assert
var ex = Assert.Throws(() => strategy.Sort(input));
Assert.That(ex.Message, Is.EqualTo("Input cannot be null. (Parameter 'input')"));
}
}
}
[TestFixture]
открытый класс SortControllerTests
{
//Bubble Sorting Test
[Test]
public void SortController_SortsUsingBubbleSort()
{
var model = new SortModel();
var controller = new SortController(model);
controller.SetSortStrategy(new BubbleSortStrategy());
string input = "befdac";
string expected = "abcdef";
controller.UpdateModel(input);
controller.Sort();
string result = controller.GetSortedString();
Assert.AreEqual(expected, result);
}
//Quick Sorting Test
[Test]
public void SortController_SortsUsingQuickSort()
{
var model = new SortModel();
var controller = new SortController(model);
controller.SetSortStrategy(new QuickSortStrategy());
string input = "befdac";
string expected = "abcdef";
controller.UpdateModel(input);
controller.Sort();
string result = controller.GetSortedString();
Assert.AreEqual(expected, result);
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... n-mvc-code
Что не так с моим кодом MVC для разработки стратегии? [закрыто] ⇐ C#
Место общения программистов C#
-
Anonymous
1721729488
Anonymous
Мне интересно мнение очень опытных программистов о том, какие улучшения необходимы для того, чтобы этот код прошел. Я не понимаю, почему это не удалось, и хотел бы расширить свои знания, получив отзывы экспертов.
Экзамен по программированию
[b]Это экзамен< /strong>
Создайте приложение формы Windows, отвечающее следующим требованиям на C#.
Основная функция программы — сортировка строки с входными данными. от пользователя.
Пример ввода: befdac
Ожидаемый результат: abcdef
Пользовательский интерфейс будет содержать следующие четыре элемента:
Текстовое поле, позволяющее пользователю вводить строку. Элемент управления (
например, поле со списком), который выбирает стратегию. использовать для сортировки строки.
Кнопка, которая будет сортировать строку с использованием выбранной стратегии.
Метка, на которой будут отображаться выходные данные (отсортированная строка)
Целью задания является реализация ШАБЛОНОВ ДИЗАЙНА.[/b]
a. Шаблон стратегии: шаблон проектирования программного обеспечения, который позволяет выбирать поведение алгоритма во время выполнения. Шаблон стратегии будет использоваться для сортировки строк в двух разных реализациях. Вы можете выбрать два метода сортировки: пузырьковая сортировка, быстрая сортировка или сортировка слиянием.
b. Что касается логики и представления приложения, оно будет реализовано в шаблоне Модель-Представление-Контроллер, и вам не разрешено использовать для этого структуру.
Обязательно соблюдайте соответствующие правила. практики разработки и обеспечить наличие всех проверок. Напишите модульные тесты для отдельных компонентов вашего кода, чтобы получить преимущество.
[b]Мой код[/b]
Интерфейс
public interface ISortStrategy
{
string Sort(string input);
}
Контроллер
namespace YouSourceCodingExam.Controller
{
public class SortController
{
private readonly SortModel _model;
private ISortStrategy _strategy;
public SortController(SortModel model)
{
_model = model;
}
public void SetSortStrategy(ISortStrategy strategy)
{
_strategy = strategy;
}
public void Sort()
{
if (_strategy != null)
{
_model.Sorted = _strategy.Sort(_model.Input);
}
}
public void UpdateModel(string input)
{
_model.Input = input;
}
public string GetSortedString()
{
return _model.Sorted;
}
}
}
Модель
public class SortModel
{
public string Input { get; set; }
public string Sorted { get; set; }
}
Конкретные стратегии
public class BubbleSortStrategy : ISortStrategy
{
//BUBBLE SORT STRATEGY
public string Sort(string input)
{
//Repeatedly steps through the list, compares elements, and swaps them if they are
//in the wrong order.This process is repeated until the list is sorted.
if (string.IsNullOrEmpty(input)) return input;
char[] str = input.ToCharArray();
for (int i = 0; i < str.Length - 1; i++)
{
for (int j = 0; j < str.Length - i - 1; j++)
{
if (str[j] > str[j + 1])
{
// Swap str[j] and str[j+1]
char t = str[j];
str[j] = str[j + 1];
str[j + 1] = t;
}
}
}
return new string(str);
//OR USING LINQ
var sortedChars = input.OrderBy(c => c);
return new string(sortedChars.ToArray());
}
}
public class QuickSortStrategy : ISortStrategy
{
//QUICK SORT STRATEGY
public string Sort(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input), "Input cannot be null.");
if (input.Length == 0)
return input;
char[] str = input.ToCharArray();
QSort(str, 0, str.Length - 1);
return new string(str);
}
private void QSort(char[] str, int l, int h)
{
if (l < h)
{
int pi = Split(str, l, h);
//Iterate repetitively before spllitting
QSort(str, l, pi - 1);
QSort(str, pi + 1, h);
}
}
//Method to split or partition the string array
private int Split(char[] str, int l, int h)
{
char p = str[h];
int i = (l - 1); //smaller element
for (int j = l; j < h; j++)
{
//if current is smaller than or equal to p
if (str[j] < p)
{
i++;
char t = str[i];
str[i] = str[j];
str[j] = t;
}
}
char s = str[i + 1];
str[i + 1] = str[h];
str[h] = s;
return i + 1;
}
}
Просмотр
public partial class MainForm : Form
{
private readonly SortModel _model;
private readonly SortController _controller;
public MainForm()
{
InitializeComponent();
_model = new SortModel();
_controller = new SortController(_model);
// Populate ComboBox with sorting strategies
comboBoxSortStrategy.Items.Add("Bubble Sort");
comboBoxSortStrategy.Items.Add("Quick Sort");
comboBoxSortStrategy.SelectedIndex = 0;
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void buttonSort_Click(object sender, EventArgs e)
{
string input = textBoxInput.Text;
// Validate the input
if (string.IsNullOrEmpty(input))
{
MessageBox.Show("Input string cannot be null or empty.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_controller.UpdateModel(input);
// Set the sorting strategy based on ComboBox selection
ISortStrategy strategy;
string selectedStrategy = comboBoxSortStrategy.SelectedItem.ToString();
if (selectedStrategy == "Bubble Sort")
{
strategy = new BubbleSortStrategy();
}
else if (selectedStrategy == "Quick Sort")
{
strategy = new QuickSortStrategy();
}
else
{
throw new InvalidOperationException("Invalid sorting strategy selected");
}
_controller.SetSortStrategy(strategy);
_controller.Sort();
labelOutput.Text = _controller.GetSortedString();
}
private void comboBoxSortStrategy_SelectedIndexChanged(object sender, EventArgs e)
{
labelOutput.Text = "";
textBoxInput.Text = "";
}
}
Модульное тестирование
namespace YouSourceCodingExamTest
{
[TestFixture]
public class SortStrategyTests
{
//Sorting Test
[Test]
public void BubbleSort_SortsCorrectly()
{
// Arrange
var strategy = new BubbleSortStrategy();
string input = "befdac";
string expected = "abcdef";
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_SortsCorrectly()
{
// Arrange
var strategy = new QuickSortStrategy();
string input = "befdac";
string expected = "abcdef";
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
//Empty String Test
[Test]
public void BubbleSort_EmptyString_ReturnsEmpty()
{
var strategy = new BubbleSortStrategy();
string input = "";
string expected = "";
string result = strategy.Sort(input);
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_EmptyString_ReturnsEmpty()
{
var strategy = new QuickSortStrategy();
string input = "";
string expected = "";
string result = strategy.Sort(input);
Assert.AreEqual(expected, result);
}
//Validation Test
[Test]
public void BubbleSort_NullString_ReturnsNull()
{
// Arrange
var strategy = new BubbleSortStrategy();
string input = null;
string expected = null;
// Act
string result = strategy.Sort(input);
// Assert
Assert.AreEqual(expected, result);
}
[Test]
public void QuickSort_NullString_ThrowsArgumentNullException()
{
// Arrange
var strategy = new QuickSortStrategy();
string input = null;
// Act & Assert
var ex = Assert.Throws(() => strategy.Sort(input));
Assert.That(ex.Message, Is.EqualTo("Input cannot be null. (Parameter 'input')"));
}
}
}
[TestFixture]
открытый класс SortControllerTests
{
//Bubble Sorting Test
[Test]
public void SortController_SortsUsingBubbleSort()
{
var model = new SortModel();
var controller = new SortController(model);
controller.SetSortStrategy(new BubbleSortStrategy());
string input = "befdac";
string expected = "abcdef";
controller.UpdateModel(input);
controller.Sort();
string result = controller.GetSortedString();
Assert.AreEqual(expected, result);
}
//Quick Sorting Test
[Test]
public void SortController_SortsUsingQuickSort()
{
var model = new SortModel();
var controller = new SortController(model);
controller.SetSortStrategy(new QuickSortStrategy());
string input = "befdac";
string expected = "abcdef";
controller.UpdateModel(input);
controller.Sort();
string result = controller.GetSortedString();
Assert.AreEqual(expected, result);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78782664/what-is-wrong-with-my-strategy-design-mvc-code[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия