Skip to content

Instantly share code, notes, and snippets.

@StrikerXx798
Last active June 18, 2025 18:49
Show Gist options
  • Save StrikerXx798/08613a59da079187bf1efc28a4e636f7 to your computer and use it in GitHub Desktop.
Save StrikerXx798/08613a59da079187bf1efc28a4e636f7 to your computer and use it in GitHub Desktop.
ДЗ: Супермаркет
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class Program
{
static void Main(string[] args)
{
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
var supermarket = new Supermarket();
supermarket.Run();
}
}
static class RandomUtils
{
private static readonly Random _random = new Random();
public static int Next(int minValue, int maxValue)
{
return _random.Next(minValue, maxValue);
}
public static int Next(int maxValue)
{
return _random.Next(maxValue);
}
}
class Supermarket
{
private const int CommandServeNext = 1;
private const int CommandAddCustomer = 2;
private const int CommandShowQueue = 3;
private const int CommandShowProducts = 4;
private const int CommandShowEarnings = 5;
private const int CommandExit = 6;
private const int MinProductsInCart = 1;
private const int MaxProductsInCart = 6;
private const int InitialCustomersCount = 3;
private readonly List<Product> _products;
private readonly Queue<Customer> _customers;
private int _earnedMoney;
public Supermarket()
{
_products = new List<Product>
{
new Product("Яблоко", 50),
new Product("Груша", 40),
new Product("Банан", 70),
new Product("Манго", 100),
new Product("Дыня", 60),
new Product("Арбуз", 300)
};
_customers = new Queue<Customer>();
_earnedMoney = 0;
for (int i = 0; i < InitialCustomersCount; i++)
{
_customers.Enqueue(CreateRandomCustomer());
}
}
public void Run()
{
bool isRunning = true;
while (isRunning)
{
ShowMenu();
int command = GetNumberInput("Введите команду:");
switch (command)
{
case CommandServeNext:
ServeNext();
break;
case CommandAddCustomer:
AddCustomer();
break;
case CommandShowQueue:
ShowQueue();
break;
case CommandShowProducts:
ShowProducts();
break;
case CommandShowEarnings:
ShowEarnings();
break;
case CommandExit:
isRunning = false;
break;
default:
Console.WriteLine("Неизвестная команда. Попробуйте снова.");
break;
}
}
}
private void ShowMenu()
{
Console.WriteLine();
Console.WriteLine($"{CommandServeNext} - Обслужить следующего клиента");
Console.WriteLine($"{CommandAddCustomer} - Добавить клиента в очередь");
Console.WriteLine($"{CommandShowQueue} - Показать очередь клиентов");
Console.WriteLine($"{CommandShowProducts} - Показать товары супермаркета");
Console.WriteLine($"{CommandShowEarnings} - Показать заработанные деньги");
Console.WriteLine($"{CommandExit} - Выйти");
}
private int GetNumberInput(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
int number;
while (!int.TryParse(input, out number))
{
Console.WriteLine("Некорректный ввод. Попробуйте снова.");
input = Console.ReadLine();
}
return number;
}
private void ShowProducts()
{
Console.WriteLine("Товары супермаркета:");
foreach (var product in _products)
{
product.ShowInfo();
}
}
private void ShowQueue()
{
if (_customers.Count == 0)
{
Console.WriteLine("Очередь пуста.");
return;
}
int i = 1;
foreach (var customer in _customers)
{
Console.WriteLine($"{i++}. Клиент с {customer.Money} руб., товаров в корзине: {customer.CartCount}");
}
}
private void AddCustomer()
{
_customers.Enqueue(CreateRandomCustomer());
Console.WriteLine("Клиент добавлен в очередь.");
}
private Customer CreateRandomCustomer()
{
int productsCount = RandomUtils.Next(MinProductsInCart, MaxProductsInCart + 1);
var cart = new List<Product>();
for (int i = 0; i < productsCount; i++)
{
Product product = _products[RandomUtils.Next(_products.Count)];
cart.Add(product);
}
return new Customer(cart);
}
private void ServeNext()
{
if (_customers.Count == 0)
{
Console.WriteLine("Очередь пуста.");
return;
}
var customer = _customers.Dequeue();
Console.WriteLine($"Обслуживается клиент с {customer.Money} руб.");
Console.WriteLine("Корзина:");
customer.ShowCart();
int total = customer.GetCartTotal();
TryRemoveProductsUntilAffordable(customer, ref total);
if (customer.CartCount == 0)
{
Console.WriteLine("Клиент не смог купить ни одного товара.");
return;
}
customer.Pay(total);
_earnedMoney += total;
customer.MoveCartToBag();
Console.WriteLine($"Покупка совершена на сумму {total} руб. Осталось денег: {customer.Money} руб.");
Console.WriteLine("Купленные товары:");
customer.ShowBag();
}
private void TryRemoveProductsUntilAffordable(Customer customer, ref int total)
{
while (total > customer.Money && customer.CartCount > 0)
{
int removeIndex = RandomUtils.Next(customer.CartCount);
Product removed = customer.RemoveFromCart(removeIndex);
Console.WriteLine($"Клиент не может оплатить покупку. Удалён товар: {removed.Name} ({removed.Price} руб.)");
total = customer.GetCartTotal();
}
}
private void ShowEarnings()
{
Console.WriteLine($"Всего заработано: {_earnedMoney} руб.");
}
}
class Product
{
private int _nextId = 1;
public Product(string name, int price)
{
Id = _nextId++;
Name = name;
Price = price;
}
public int Id { get; }
public string Name { get; }
public int Price { get; }
public void ShowInfo()
{
Console.WriteLine($"ID: {Id}, Название: {Name}, Цена: {Price}");
}
}
class Customer
{
private const int MinCustomerMoney = 500;
private const int MaxCustomerMoney = 2000;
private readonly List<Product> _cart;
private readonly List<Product> _bag;
public Customer(List<Product> cart)
{
Money = RandomUtils.Next(MinCustomerMoney, MaxCustomerMoney + 1);
_cart = cart;
_bag = new List<Product>();
}
public int Money { get; private set; }
public int CartCount => _cart.Count;
public int GetCartTotal()
{
int sum = 0;
foreach (var product in _cart)
sum += product.Price;
return sum;
}
public void ShowCart()
{
if (_cart.Count == 0)
{
Console.WriteLine("Корзина пуста.");
return;
}
foreach (var product in _cart)
product.ShowInfo();
}
public void ShowBag()
{
if (_bag.Count == 0)
{
Console.WriteLine("Сумка пуста.");
return;
}
foreach (var product in _bag)
product.ShowInfo();
}
public Product RemoveFromCart(int index)
{
Product product = _cart[index];
_cart.RemoveAt(index);
return product;
}
public void Pay(int amount)
{
Money -= amount;
}
public void MoveCartToBag()
{
_bag.AddRange(_cart);
_cart.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment