开发者

Selecting combination using linq

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 ove开发者_高级运维r.Ofcourse in next interview nobody will ask it to do).


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜