Skip to content

Instantly share code, notes, and snippets.

@GigaOrts
Created September 18, 2023 13:13
Show Gist options
  • Save GigaOrts/36b6627f35a00302ec86f746babfa3a7 to your computer and use it in GitHub Desktop.
Save GigaOrts/36b6627f35a00302ec86f746babfa3a7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
ClientsFactory factory = new ClientsFactory();
Supermarket supermarket = new Supermarket();
supermarket.Run(factory.GenerateClients());
}
}
class ClientsFactory
{
public Queue<Client> GenerateClients()
{
int maxClients = 5;
Queue<Client> clients = new Queue<Client>();
int minBalance = 10;
int maxBalance = 50;
for (int i = 0; i < maxClients; i++)
{
int money = UserUtils.GetRandomNumber(minBalance, maxBalance);
clients.Enqueue(new Client(money));
}
return clients;
}
}
class Supermarket
{
Queue<Client> _clients;
List<Product> _products;
public Supermarket()
{
_products = new List<Product>()
{
new Product(10),
new Product(10),
new Product(10),
new Product(10),
};
}
public void Run(Queue<Client> clients)
{
_clients = new Queue<Client>(clients);
ProcessShopping();
ServeClients();
}
private void ServeClients()
{
while (_clients.Count > 0)
{
Client client = _clients.Dequeue();
while (client.CanPay == false)
client.RemoveRandomProduct();
}
}
private void ProcessShopping()
{
foreach (Client client in _clients)
{
int maxClients = 5;
int repeats = UserUtils.GetRandomNumber(maxClients);
for (int i = 0; i < repeats; i++)
{
int randomProductIndex = UserUtils.GetRandomNumber(_products.Count);
Product product = _products[randomProductIndex];
client.Add(product);
}
}
}
}
class Client
{
private readonly List<Product> _products;
private readonly int _money;
public Client(int money)
{
_money = money;
_products = new List<Product>();
}
public bool CanPay => _money > GetTotalPrice();
public void Add(Product product)
{
_products.Add(product);
}
public void RemoveRandomProduct()
{
int randomIndex = UserUtils.GetRandomNumber(_products.Count);
_products.RemoveAt(randomIndex);
}
private int GetTotalPrice()
{
int sum = 0;
foreach (var item in _products)
{
sum += item.Price;
}
return sum;
}
}
class Product
{
public Product(int price)
{
Price = price;
}
public int Price { get; }
}
class UserUtils
{
private static readonly Random s_random = new Random();
public static int GetRandomNumber(int minValue, int maxValue)
{
return s_random.Next(minValue, maxValue);
}
public static int GetRandomNumber(int maxValue)
{
return s_random.Next(maxValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment