Comment detail

FizzBuzz問題の一般化 (Nested Flatten)
LINQが便利すぎる。
エラー処理は適当です。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
static void Main(string[] args)
{
    FizzBuzz( 101,120, "3","Pizz","5","Quzz","7","Razz" );
    FizzBuzz(   1, 20, "3","Fizz","5","Buzz" );
}

static public void FizzBuzz(int from, int to, params string[] kv)
{
    if (kv.Length % 2 != 0 || from > to )
        return;

    Dictionary<int, string> fbPair = new Dictionary<int, string>();

    try
    {
        for (int i = 0; i < kv.Length; i += 2)
        {
            fbPair.Add(int.Parse(kv[i]), kv[i + 1]);
        }
    }
    catch (Exception)
    {
        return;
    }

    for (int i = from; i <= to; ++i)
    {
        var x = from y in fbPair
                where i % y.Key == 0
                orderby y.Key ascending
                select y.Value;

        StringBuilder    outStr = new StringBuilder();

        foreach( string v in x )
        {
            outStr.Append( v );
        }

        Console.WriteLine("{0," + to.ToString().Length + "}:{1}", i, outStr.Length != 0 ? outStr.ToString() : "hoge" );
    }
}
C#3.0勉強中です.LINQは面白いですね.
空の時のデフォルト値と文字列の連結にもLINQ使ってみました.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Text;
using System.Linq;

class Program {
    class FBMatch {
        public int n;
        public string s;
    };
    static void Main(string[] args) {
        FizzBuzz(101, 120, new FBMatch{n=3, s="Pizz"},
            new FBMatch{n=5, s="Quzz"}, new FBMatch{n=7, s="Razz"});
        FizzBuzz(1, 20, new FBMatch{n=3, s="Fizz"}, new FBMatch{n=5, s="Buzz"});
    }
    static void FizzBuzz(int from, int to, params FBMatch[] table) {
        var format = "{0," + to.ToString().Length + "}:{1}";

        for (var i = from; i <= to; i++) {
            var x = from y in table where i % y.n == 0 select y.s;

            Console.WriteLine(format, i, x.DefaultIfEmpty("hoge")
                .Aggregate(new StringBuilder(), (sb, s) => sb.Append(s)));
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...