Pregunta

For example, if I wanted to create a program that gives a person a discount based on how many items they have. If they were to purchase 0-5 items they do not get a discount. If they purchase 5-10 items they get a 5% discount, if they get 10-20 items they get a 10% discount and so forth. How can I use an array to sort this out instead of many "If" statements?

¿Fue útil?

Solución 2

You can maintain an array to represent the ranges you have given. I am talking about storing like.... say array name is array then array[0]=5 ie the max value of the first interval. then array[1]=10 max value of second interval and proceed in the same way. since this array you just maintained will only contain small number of value so no performance issue with linear search. Now if the numberOfOrderedItems are less than value_of_array you can break the loop and decide the discount you want to give.

If you are maintaining huge number of discount intervals then go for binary search instead of linear search.

Otros consejos

How about starting with a structure to store the bounds and discount:

public struct DiscountSpec
{
   public int MinItems{get;set;}
   public int MaxItems{get;set;}
   public double Discount{get;set;}
}

put it in an array

DiscountSpec[] discounts = new DiscountSpec[]
{
   new DiscountSpec(){MinItems=0,MaxItems=5,Discount=0},
   new DiscountSpec(){MinItems=5,MaxItems=10,Discount=0.05},
   new DiscountSpec(){MinItems=10,MaxItems=20,Discount=0.10},
}

And then the magic

int numItemsPurchased=7;
var discount = discounts.Where(
      d => d.MinItems<numItemsPurchased && d.MaxItems>=numItemsPurchased)
                        .Select(d => d.Discount)
                        .FirstOrDefault();

Now, discount will contain either 0 (no discount) or 0.05 (5% discount) or 0.1 (10% discount). This can be extended with other discount brackets if need be.

Live example: http://rextester.com/YDOWS85239

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top