gpt4 book ai didi

performance - Linq 解谜器

转载 作者:行者123 更新时间:2023-12-04 02:46:03 27 4
gpt4 key购买 nike

我很无聊,决定尝试使用 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 这么慢?

最佳答案

一方面,您只是在生成了整组 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 };

关于performance - Linq 解谜器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8154474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com