ようこそ。睡眠不足なプログラマのチラ裏です。

LINQで虫食い算的なもの

以前書いた、Haskellで虫食い算的なものと同じ問題を、LINQで解いてみる。

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 虫食い算
            //    4○○
            //   × ○○
            //   --------
            // ○○○○○
            // ※ただし、○には4を除く0〜9の数字を1つずつ使用
            //   また、桁の先頭は0ではないこと。

            var items = Enumerable.Range(0,4).Concat(Enumerable.Range(5,5));
            var answers =
                        from a in items
                        from b in items.Except(new[] { a })
                        from c in items.Except(new[] { a, b })
                        from d in items.Except(new[] { a, b, c })
                        from e in items.Except(new[] { a, b, c, d })
                        from f in items.Except(new[] { a, b, c, d, e })
                        from g in items.Except(new[] { a, b, c, d, e, f })
                        from h in items.Except(new[] { a, b, c, d, e, f, g })
                        from i in items.Except(new[] { a, b, c, d, e, f, g, h })
                        let x = 4 * 100 + a * 10 + b
                        let y = c * 10 + d
                        let z = e * 10000 + f * 1000 + g * 100 + h * 10 + i
                        where (x * y) == z
                        where c != 0
                        where e != 0
                        select new { X = x, Y = y, Z = z };

            foreach (var a in answers) {
                Console.WriteLine(a);
            }
            Console.WriteLine("\(^o^)/オワタ");
            Console.Read();
        }
    }
}


実行結果

{ X = 402, Y = 39 , Z = 15678 }
{ X = 495, Y = 36 , Z = 17820 }
\(^o^)/オワタ

はいよくできましたー

Haskellの方が早く算出できるなあ。当たり前か。