views:

83

answers:

2

This is also one of the interview question i have faced recently.

Description :

The task is $ 100(Please consider some currency) will be given to me.I need to purchase three items itemA,itemB,itemC.The cost of (I am not sure 0.25$ or 0.75 $ are meaningful,so think it as other currency) itemA=0.25$,itemB=0.75$ and itemC=20$. I need to purchase 100 items exactly at 100$ ( I can purchase any number of itemA,itemB,ItemC but 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 got the 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 task was to give the demo using "linq".How can i solve the same using Linq?

(Anyhow the interview was over.Ofcourse in next interview nobody will ask it to do).

+4  A: 
    var a = from i in Enumerable.Range(1, 100) 
            from j in Enumerable.Range(1, 100) 
            from k in Enumerable.Range(1, 20) select new { i, j, k };
    var b = a.Where(p => (p.i * 0.25) + (p.j * 0.75) + (p.k * 5) == 100 
                && (p.i + p.j + p.k) == 100);
    foreach (var e in b) 
        Console.WriteLine("item1={0},item2={1},item3={2}", 
                            e.i, e.j, e.k);
DreamWalker
+5  A: 
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);
dahlbyk