Linq拼图解算器

时间:2011-11-16 15:49:30

标签: performance linq puzzle

我很无聊,决定尝试使用Linq解决逻辑难题。我发现了一个谜题here

我创建的linq如下:

  IEnumerable<int> values = Enumerable.Range(1, 9);

  var result = from A in values
               from B in values
               from C in values
               from D in values
               from E in values
               from F in values
               from G in values
               from H in values
               from I in values
               where A != B && A != C && A != D && A != E && A != F && A != G && A != H && A != I
               where B != C && B != D && B != E && B != F && B != G && B != H && B != I
               where C != D && C != E && C != F && C != G && C != H && C != I
               where D != E && D != F && D != G && D != H && D != I
               where E != F && E != G && E != H && E != I
               where F != G && F != H && F != I
               where G != H && G != I
               where H != I
               where A + B == 11
               where B + C + D == 11
               where D + E + F == 11
               where F + G + H == 11
               where H + I == 11
               select new { A, B, C, D, E, F, G, H, I };

  result.ToList().ForEach(x => Console.WriteLine("A: {0}, B: {1}, C: {2}, D: {3}, E: {4}, F: {5}, G: {6}, H: {7}, I: {8}", x.A, x.B, x.C, x.D, x.E, x.F, x.G, x.H, x.I));

我希望这可以很容易地打印所有答案,但它似乎只是永远计算。如果我以标准方式写这个,那么计算答案需要几微秒。为什么linq这么慢?

2 个答案:

答案 0 :(得分:7)

嗯,首先,你只是在之后过滤,你已经生成了整套9个值。你可以像这样提高效率:

from A in values
from B in values
where B != A
where A + B == 11
from C in values
where C != A && C != B
from D in values
where D != A && D != B && D != C
where B + C + D == 11
from E in values
where E != A && E != B && E != C && E != D
from F in values
where F != A && F != B && F != C && F != D && F != E
where D + E + F == 11
from G in values
where G != A && G != B && G != C && G != D && G != E && G != F
from H in values
where H != A && H != B && H != C && H != D && H != E && H != F && H != G
where F + G + H == 11
from I in values
where I != A && I != B && I != C && I != D && I != E && I != F && I != G && H != I
where H + I == 11
select new { A, B, C, D, E, F, G, H, I };

答案 1 :(得分:3)

您正在计算超过9个值序列的笛卡尔积,因此您有9个 9 = 387420489个输入元素。那将是非常缓慢的。相反,您应该先修剪 ,这样您就不必首先计算不必要的输入值。