Skip to content

Instantly share code, notes, and snippets.

@gavilanch
Created February 10, 2023 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavilanch/67ca7522ae02e3312d9f15106531d5da to your computer and use it in GitHub Desktop.
Save gavilanch/67ca7522ae02e3312d9f15106531d5da to your computer and use it in GitHub Desktop.
Codigo para algoritmo determina que productos se pueden comprar con un giftcard
[DebuggerDisplay("{Nombre} ({Precio})")]
internal class Producto : IComparable
{
public Producto(string nombre, decimal precio)
{
Nombre = nombre;
Precio = precio;
}
public string Nombre { get; set; }
public decimal Precio { get; set; }
public int CompareTo(object? obj)
{
if (obj is Producto p2)
{
return Nombre.CompareTo(p2.Nombre);
}
throw new Exception("Objeto debe ser producto");
}
}
using ConsoleApp10;
var productos = new List<Producto>()
{
new Producto("p1", 50),
new Producto("p2", 300),
new Producto("p3", 90),
new Producto("p4", 60),
new Producto("p5", 100),
new Producto("p6", 20),
};
var productoCartesiano = ObtenerProductoCartesiano(productos);
var montoTarjetaRegalos = 500m;
var listadoCombinacionesProductos = ObtenerCombinacionesDeProductosTarjetaDeRegalo(montoTarjetaRegalos, productoCartesiano);
foreach (var combinacion in listadoCombinacionesProductos)
{
Console.WriteLine("--Combinacion--");
foreach (var producto in combinacion)
{
Console.WriteLine($" - {producto.Nombre} (${producto.Precio})");
}
Console.WriteLine($" => Suma = {combinacion.Sum(p => p.Precio)}");
Console.WriteLine();
}
List<List<Producto>> ObtenerCombinacionesDeProductosTarjetaDeRegalo(decimal montoTarjetaRegalos, List<IEnumerable<Producto>> productoCartesiano)
{
var resultado = new List<List<Producto>>();
foreach (var combinacion in productoCartesiano)
{
var sumaProductos = combinacion.Sum(p => p.Precio);
if (sumaProductos < montoTarjetaRegalos)
{
resultado.Add(combinacion.ToList());
}
}
return resultado;
}
List<IEnumerable<T>> ObtenerProductoCartesiano<T>(List<T> productos) where T: IComparable
{
var distintasCombinaciones = new List<List<IEnumerable<T>>>();
for (int i = 1; i <= productos.Count; i++)
{
var combinaciones = GetKCombs(productos, i).ToList();
distintasCombinaciones.Add(combinaciones);
}
var resultado = distintasCombinaciones.SelectMany(p => p).ToList();
return resultado;
}
static IEnumerable<IEnumerable<T>>
GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetKCombs(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment