Language detail: C#

Coverage: 100.00%
number of '+' ratings
contribution for coverage

Unsolved challenges

None

codes

Feed

Used modules

next >>

比較しないソートの作成 (Nested Flatten)

LINQでぴしっとはまると気持ちいいですね。基数ソートのつもりでしたが、鳩の巣ソートらしいです。Mainは#6652から持ってきました、ありがとうございます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Linq;
using System.Collections.Generic;

class C
{
    static IEnumerable<int> countingSort(int[] src, int min, int max)
    {
        var l = src.ToLookup(i => i);
        return Enumerable.Range(min, max - min + 1).SelectMany(i => l[i]);
//こう書いても同じ
//        return from i in Enumerable.Range(min, max - min + 1)
//               from e in l[i]
//               select e;
    }

    static void Main()
    {
        var sort = countingSort(new int[] { -1, 9, 4, 8, 9, 6, 3, 9, 5, 2 }, -1, 9);
        foreach (var e in sort)
            Console.Write(e + " ");
    }
}
タブ区切りデータの処理 (Nested Flatten)

ファイルから読んでファイルへ書き出します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        var header =
            from line in File.ReadAllLines("inFile.txt").Take(1)
            let x = line.Split('\t')
            select x[0] + '\t' + x[2] + '\t' + x[1] + '\t' + x[3];

        var lines =
            from line in File.ReadAllLines("inFile.txt").Skip(1)
            let x = line.Split('\t')
            orderby x[0]
            select x[0] + '\t' + x[2] + '\t' + x[1] + '\t' + (int.Parse(x[3]) + 1);

        File.WriteAllLines("outFile.txt", header.Concat(lines).ToArray());
    }
}
いまいちすっきりと書けません。
 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
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Text;
using VB_IO = Microsoft.VisualBasic.FileIO;

class Program {
    static void Main(string[] args) {
        //テーブルの準備
        List<string> headers = new List<string>();
        List<List<string>> table = new List<List<string>>();

        //TSVの読み込みにはMicrosoft.VisualBasic.FileIOTextFieldParserクラスが便利。CSVにも使えるよ。
        //Microsoft.VisualBasicを参照に加えてね。
        using(VB_IO.TextFieldParser tfp = new VB_IO.TextFieldParser(args[0], Encoding.GetEncoding("shift-jis"))) {
            tfp.SetDelimiters("\t");//区切り記号はタブ

            //通常のテキストファイルと同じ感覚で扱えます。
            headers.AddRange(tfp.ReadFields());
            while(!tfp.EndOfData) {
                table.Add(new List<string>(tfp.ReadFields()));
            }

            tfp.Close();
        }

        //第1カラムの値でデータを昇順にソートする。
        table.Sort((a, b) => (int.Parse(a[0]) - int.Parse(b[0])));//何回見ても書いてもラムダ式きもい。

        //第2カラムと第3カラムをヘッダを含めて入れ替える。
        headers.Reverse(1, 2);
        foreach(List<string> row in table){
            row.Reverse(1, 2);
            //第4カラムの値にそれぞれ1を加える。
            row[3] = (int.Parse(row[3]) + 1).ToString();
        }

        //出力
        foreach(string header in headers){
            Console.Write(header + "\t");
        }
        Console.WriteLine();
        foreach(List<string> row in table) {
            foreach(string cell in row) {
                Console.Write(cell + "\t");
            }
            Console.WriteLine();
        }
    }
}
起動オプションの解析 (Nested Flatten)
 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;

class P
{
  static void Main(string[] args)
  {
    bool o = false, q =false, d = false;
    int? dn = null;
    List<string> l = new List<string>();
    try
    {
      foreach (string s in args)
      {
        if (d && (dn == null))
        {
          if (s.Length != 1) throw new Exception();
          dn = s[0] - '0';
          continue;
        }
        if (l.Count > 0 || s[0] != '-')
        {
          l.Add(s);
          continue;
        }
        for (int i = 1; i < s.Length; i++)
        {
          switch (s[i])
          {
            case 'o':
              o = true;
              break;
            case 'q':
              q = true;
              break;
            case 'd':
              d = true;
              if (i < s.Length - 1)
                dn = s[++i] - '0';
              break;
            default:
              throw new Exception(s);
          }
        }
      }
      if (!o) throw new Exception();
      if (d && !(0 <= dn && dn <= 2)) throw new Exception();
      if (l.Count == 0) throw new Exception();
      Console.WriteLine("o(output): {0}", o ? "ON" : "OFF");
      Console.WriteLine("q(quote): {0}", q ? "ON" : "OFF");
      if (d) Console.WriteLine("d(debug): {0}", dn);
      for (int i = 0; i < l.Count; i++)
        Console.WriteLine("{0}: {1}", i, l[i]);
    }
    catch
    {
      Console.WriteLine
        ("usage: cmdopt -o [-q] [-d{0|1|2}] string [string ...]");
      Environment.Exit(-1);
    }
  }
}
2^i * 3^j * 5^k なる整数 (Nested Flatten)

ちゃんと計算してないけど、時間計算量はO(n logn)、空間計算量はO(1)ぐらい? 再帰してるから空間計算量はO(logn)なのかな。

 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
class P
{
  static void Main(string[] args)
  {
    for (int i = 1, c = 0; c < 100; i++)
    {
      int[] f = F(i);
      if (f != null)
      {
        ++c;
        System.Console.WriteLine
          ("{0} = 2^{1} * 3^{2} * 5^{3}", i, f[2], f[3], f[5]);
      }
    }
  }

  static int[] F(int n)
  {
    if (n == 1) return new int[6];
    int[] a = { 2, 3, 5 };
    foreach (int d in a)
      if (n % d == 0)
      {
        int[] r = F(n / d);
        if (r == null) return null;
        ++r[d];
        return r;
      }
    return null;
  }
}
LL Golf Hole 9 - トラックバックを打つ (Nested Flatten)

今回は短くしなくて良いのですね。 こういう遊び心のあるお題、好きです。

 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
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

class Program {
    static void Main(string[] args) {
        //接続の作成
        WebClient webClient = new WebClient();
        webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

        //送信パラメータ作成
        NameValueCollection postValues = new NameValueCollection();
        postValues.Add("title",
            "LL Golf Hole 9 - トラックバックを打つ");
        postValues.Add("excerpt",
            "あにすです。面白いお題の数々、楽しませて頂きました。");
        postValues.Add("url",
            "http://ja.doukaku.org/207/");
        postValues.Add("blog_name",
            "どう書く?org");

        //トラックバック送信
        byte[] r = webClient.UploadValues("http://ll.jus.or.jp/2008/blog/archives/38/trackback", postValues);

        //テスト用
        //byte[] r = webClient.UploadValues("http://d.hatena.ne.jp/takano32/20080905", postValues);

        //後始末
        webClient.Dispose();

        //レスポンス確認
        Console.WriteLine(Encoding.UTF8.GetString(r));
        Console.ReadLine();
    }
}
文字列型日時ののN秒後時間取得 (Nested Flatten)
date = "2008/08/27 23:59:25"
addSeconds = 40
> "2008/08/28 00:00:05"
 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
using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine(
            DateEx(Console.ReadLine(), long.Parse(Console.ReadLine()))
            );
        
        Console.WriteLine(
            DateEx(long.Parse(Console.ReadLine()))
            );
        
        Console.ReadLine();
    }

    static string DateEx(string date, long addSeconds) {
        DateTime d;
        DateTime.TryParse(date, out d);
        if(d == null) throw new ArgumentException("日付が正しくありません。", "date");
        return d.AddSeconds((double)addSeconds).ToString();
    }

    static string DateEx(long addSeconds) {
        return DateEx(DateTime.Now.ToString(), addSeconds);
    }
}
LL Golf Hole 8 - 横向きのピラミッドを作る (Nested Flatten)

改行,空白を除いたバイト数:167

System.Linq.Enumerableを使う形でせめてみましたが、この辺が限界な気がする・・・。

一応手法としては以下の方式があると考えました。

  1. 2重forループ⇒先駆者が居ました
  2. Enumerableで要素生成⇒もう限界そう
  3. 再帰⇒型付言語だとかえって冗長なコードになる

1
2
3
4
5
6
7
8
9
using System;
class L
{
    static void Main(string[] a)
    {
        int n = int.Parse(a[0]);
        foreach (int m in System.Linq.Enumerable.Range(-n, n * 2)) Console.WriteLine(new string('*', n - Math.Abs(m)));
    }
}

少し短くなりました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var a = Enumerable.Range(1, args.Length != 0 ? int.Parse(args[0]) : 4);
        a.Concat(a.Reverse().Skip(1)).Select(n => new string('*', n)).ToList().ForEach(Console.WriteLine);
    }
}

実質一行になるように書いてみました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int count = args.Length != 0 ? int.Parse(args[0]) : 4;
        Enumerable.Concat(Enumerable.Range(1, count), Enumerable.Range(1, count - 1).Reverse()).Select(n => new string('*', n)).ToList().ForEach(Console.WriteLine);
    }
}
少しだけ縮みました。
タブと改行を除いて142B

1
2
3
4
5
6
7
8
class P{
    static void Main(string[]a){
        int n=int.Parse(a[0]),m,k;
        for(m=-n;m<=n;)
            for(k=++m>0?n-m:n+m;k>=0;)
                System.Console.Write(k-->0?"*":"\n");
    }
}
タブと改行を除くと148B
1
2
3
4
5
6
7
8
class P{
    static void Main(string[] a){
        int n=int.Parse(a[0]);
        for(int m=-n;m<=n;m++)
            for(int k=m>0?n-m:n+m;k>=0;)
                System.Console.Write(k-->0?"*":"\n");
    }
}
LL Golf Hole 7 - バイト数を読みやすくする (Nested Flatten)
標準入力から読み込み。
Yまで対応しています。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using System;
class P {
    static void Main() {
        double n = double.Parse(Console.ReadLine());
        string s = " kMGTPEZY";
        int c = 0, l = 1000;
        for (; n >= l; c++)
            n /= l;
        Console.WriteLine("{0:f1}{1}", n, s[c]);
    }
}
LL Golf Hole 6 - 10進数を2進数に基数変換する (Nested Flatten)
標準入力から、数値、基数(2,8,10,16)の順で。
1
2
3
4
5
6
7
8
9
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Convert.ToString(int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine())));
    }
}
tailの実装 (Nested Flatten)
C#でやってみました。
 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Text;
using System.Threading;
using System.IO;

class Tail
{
    private const int SLEEP_TIME = 1000;
    private static bool fOption = false;
    private static int outputLines = 10;
    private static string filename = string.Empty;
    private static string usage = "Usage: Tail.exe [-n number] [-f] filename";

    static void Main(string[] args)
    {
        try {
            for (int i = 0; i < args.Length; i++) {
                if (args[i][0] == '-') {
                    switch (args[i][1]) {
                        case 'n':
                            outputLines = int.Parse(args[++i]);
                            break;
                        case 'f':
                            fOption = true;
                            break;
                        default:
                            Console.Error.WriteLine("Invalid Option: {0}", args[i]);
                            Console.Error.WriteLine(usage);
                            return;
                    }
                }
                else
                    filename = args[i];
            }

            string buffer = string.Empty;
            int allLines = 0;
            string line = string.Empty;
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                using (StreamReader sr = new StreamReader(fs, Encoding.Default)) {
                    while (sr.ReadLine() != null)
                        allLines++;
                    fs.Seek(0, SeekOrigin.Begin);
                    if (allLines <= outputLines)
                        buffer = sr.ReadToEnd();
                    else {
                        for (int i = 0; i < allLines; i++) {
                            line = sr.ReadLine();
                            if (i > allLines - outputLines - 1)
                                buffer += line + "\n";
                        }
                    }

                    Console.WriteLine(buffer);

                    while (fOption) {
                        Thread.Sleep(SLEEP_TIME);
                        while ((line = sr.ReadLine()) != null)
                            Console.WriteLine(line);
                    }
                }
            }
        }
        catch (Exception ex) {
            Console.Error.WriteLine(ex.Message.ToString());
            Console.Error.WriteLine(usage);
        }
    }
}
LL Golf Hole 5 - 最上位の桁を数え上げる (Nested Flatten)
こんな感じで。
1
using System;class P{static void Main(string[]a){for(int i=0;i<=int.Parse(a[0]);i++)if(i%Math.Pow(10,i.ToString().Length-1)==0)Console.WriteLine(i);}}
1
2
3
4
5
6
7
class Program {
    static void Main(string[] args) {
        for (int i = 0; i <= int.Parse(args[0]); i++)
            if (System.Text.RegularExpressions.Regex.IsMatch(i.ToString(), "^.0*$"))
                System.Console.WriteLine("{0}", i);
    }
}
echoクライアント (Nested Flatten)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.IO;
using System.Net.Sockets;

class P
{
    static void Main(string[] args)
    {
        TcpClient c = new TcpClient(args[0], int.Parse(args[1]));
        NetworkStream s = c.GetStream();
        TextWriter w = new StreamWriter(s);
        TextReader r = new StreamReader(s);
        string l = null;
        while ((l = Console.ReadLine()) != null)
        {
            w.WriteLine(l);
            w.Flush();
            Console.WriteLine(r.ReadLine());
        }
    }
}
LL Golf Hole 4 - 文章から単語の索引を作る (Nested Flatten)
標準入力から読み込み。スペース・改行を省いたら363byte。
そういえば C#ってカンマ演算子使えないんですね。短くならないわけだ。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Text.RegularExpressions;
class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<String, int>();
        var n = 1;
        for (var s = "" ; (s = Console.ReadLine()) != null ; n++)
            new Regex("\\w+").Replace(s, delegate(Match m)
            {
                var k = m.ToString();
                if (!d.ContainsKey(k)) d[k] = n;
                return k;
            });
        foreach (var k in d)
            Console.Write("{0}: {1}\n", k.Key, k.Value);
    }
}
どうやっても短くならないです。
1
using System;using System.Collections.Generic;using System.IO;using System.Net;class P{static void Main(){char[]c=new char[]{' ',',','.','\'',';',':','-','?','\n','\r','(',')','/','\\','<','>','\"'};Dictionary<string,List<int>>d=new Dictionary<string,List<int>>();StreamReader s=new StreamReader(WebRequest.Create("http://www.gnu.org/licenses/gpl.txt").GetResponse().GetResponseStream());for(int l=1;!s.EndOfStream;l++){foreach(string t in s.ReadLine().Split(c)){string w=t.Trim().ToLower();if(w!="")if(d.ContainsKey(w)){if(!d[w].Contains(l))d[w].Add(l);}else d.Add(w,new List<int>(new int[]{l}));}}List<string>k=new List<string>(d.Keys);k.Sort((x,y)=>{int r=d[y].Count-d[x].Count;if(r==0){r=d[x][0]-d[y][0];}return r;});foreach(string m in k){Console.WriteLine("<<"+m+">>"+" "+d[m].Count+"回");foreach(int u in d[m]){Console.Write(u.ToString()+", ");}Console.WriteLine("\n");}Console.ReadLine();}}
next >>

Index

Feed

Other

Link

Pathtraq

loading...