Choosing a combination using linq

This is also one of the interview questions I ran into recently.

Description:

The challenge is $ 100 (please note some currency). I need to purchase three items itemA, itemB, itemC. Cost (I'm not sure if $ 0.25 or $ 0.75 makes sense, so think of it like a different currency) itemA = $ 0.25, itemB = $ 0.75 and itemC = $ 20. I need to buy 100 items for exactly $ 100 (I can buy any number of items itemA, itemB, ItemC, but the total should be 100).

Solution: Using for loop I solved it.

 for (int i = 1; i <= 100; i++)
   {
     for (int j = 1; j <= 100; j++)
     {
       for (int k = 1; k <= 20; k++)
        {
           if ((i * 0.25) + (j * 0.75) + (k * 5) == 100 && (i+j+k)==100)
           {
              Console.WriteLine("item1={0},item2={1},item3={2}", i, j, k);
            }
        }
     }
  }

      

<i> I got results too.

item1=1 , item2=93,item3=6 // cost =100,items=100

item1=18,item2=74,item3=8 //cost=100,items=100

item1=35,item2=55,item3=10 //cost=100,items=100

item1=52,item2=36,item3=12 //cost=100,items=100

item1=69,item2=17,item3=14 //cost=100,items=100

      

The actual challenge was to give a demo using "linq". How can I solve the same using Linq?

(In any case, the interview has passed. In the next interview, no one will ask for it).

+2


source to share


1 answer


var r = from i in Enumerable.Range(1, 100) 
        from j in Enumerable.Range(1, 100) 
        from k in Enumerable.Range(1, 20)
        where (i * 0.25) + (j * 0.75) + (k * 5) == 100 && (i+j+k)==100
        select string.Format("item1={0},item2={1},item3={2}", i, j, k);

foreach (var line in r) 
    Console.WriteLine(line);

      



+6


source







All Articles