Language detail: C#

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

Unsolved challenges

codes

Feed

Used modules

next >>

バイナリクロック (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
using System;
using System.Linq;

namespace ConsoleApplication {
    class Program {
        static void Main(string[] args) {
            // 現在の時刻を表示する
            BinaryClock bc = new BinaryClock();
            Console.WriteLine(bc.ToString());

            // 指定した時刻を表示する
            DateTime dt = new DateTime(2009, 1, 1, 20, 18, 0);
            Console.WriteLine(bc.ToString(dt));
            Console.ReadLine();
        }
    }

    public class BinaryClock {
        private static string ToBinString(int num, int width) {
            string format = string.Format("{{0,{0}}}", width);
            string s = String.Format(format,
                                     System.Convert.ToString(num, 2));
            return s.Aggregate("", (t, c) => t + (c == '1' ? '■' : '□'));
        }

        public string ToString(DateTime dateTime) {
            return " " + ToBinString(dateTime.Hour, 5) + "\n" +
                   ToBinString(dateTime.Minute, 6);
        }

        public override string ToString() {
            return ToString(DateTime.Now);
        }
    }
}
与えられた文字列でピラミッド (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
using System;
using System.Linq;

namespace Sample {
    class Program {
        static void Main(string[] args) {
            Pyramid("hoge");
            Pyramid("abracadabra");
            Console.ReadLine();
        }

        static void Pyramid(string s) {
            int length = s.Length;
            for (int n = 0; n < length; n++) {
                // 左側の空白を表示
                int spCount = length - n - 1;
                Console.Write(new string(' ', spCount));
                // 右側の文字部分を表示
                var ls = s.Skip(spCount);
                foreach (var c in ls)
                    Console.Write(c + " ");
                Console.WriteLine();
            }
        }
    }
}
与えられた数字のケタ数 (Nested Flatten)
LogもPowも文字列も使わない方法で。 ループの中で、WriteLineしてるのは、気に入らないけど、ご容赦を。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  void DigitNumber(int n) {
      int a = 10;
      for (int i = 1; ; i++) {
          if (n < a) {
              Console.WriteLine("{0},{1}", i, a / 10);
              break;
          }
          a *= 10;
      }
  }
文字列で+を表示する (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
using System;
using System.Linq;

class Program {
    static void Main(string[] args) {
        string loop = args[0] + args[0][0];
        string reverse = new string(loop.ToCharArray().Reverse().ToArray());

        Console.WriteLine(new string(' ', args[0].Length) + loop);

        hoge(args[0]);

        Console.WriteLine(loop + new string(' ', args[0].Length - 1) + loop);

        for(int i = 0; i < args[0].Length - 1; i++) {
            Console.WriteLine(args[0][args[0].Length - (i + 1)] + new string(' ', args[0].Length * 3 - 1) + args[0][i + 1]);
        }

        Console.WriteLine(reverse + new string(' ', args[0].Length - 1) + reverse);

        hoge(args[0]);

        Console.WriteLine(new string(' ', args[0].Length) + reverse);
    }

    private static void hoge(string arg) {
        for(int i = 0; i < arg.Length - 1; i++) {
            Console.WriteLine(new string(' ', arg.Length) + arg[arg.Length - (i + 1)] + new string(' ', arg.Length - 1) + arg[i + 1]);
        }
    }
}
ピラミッドを作る (Nested Flatten)

String.PadLeftメソッドを利用しました。

1
2
3
4
5
6
static void Pyramid(int n) {
    for (int i = 0; i < n; i++) {
        string s = new string('*', i * 2 + 1);
        Console.WriteLine(s.PadLeft(n+i));
    }
}
箱詰めパズルの判定 (Nested Flatten)

ごちゃごちゃと長くなってしまったが、答えは出たっぽいので投稿。組み合わせ数:11、重複の無い詰め方数:15

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace hakodume
{
    class Program
    {
        static void Main(string[] args)
        {
            var a1 = new Mino(new int[,]{
                            {1,1,1,1}
                        }, 1);
            var a2 = new Mino(new int[,]{
                            {1},
                            {1},
                            {1},
                            {1}
                        }, 1);

            var b = new Mino(new int[,]{
                            {2,2},
                            {2,2}
                       }, 2);

            var c1 = new Mino(new int[,]{
                            {3,3,3},
                            {0,3,0}
                        },3);
            var c2 = new Mino(new int[,]{
                            {3,0},
                            {3,3},
                            {3,0}
                        },3);
            var c3 = new Mino(new int[,]{
                            {0,3},
                            {3,3},
                            {0,3}
                        },3);
            var c4 = new Mino(new int[,]{
                            {0,3,0},
                            {3,3,3}
                        },3);
            var d1 = new Mino(new int[,]{
                            {4,4,4},
                            {4,0,0}
                        },4);
            var d2 = new Mino(new int[,]{
                            {4,4},
                            {0,4},
                            {0,4}
                        },4);
            var d3 = new Mino(new int[,]{
                            {0,0,4},
                            {4,4,4}
                        },4);
            var d4 = new Mino(new int[,]{
                            {4,0},
                            {4,0},
                            {4,4}
                        },4);
            var e1 = new Mino(new int[,]{
                            {5,5,0},
                            {0,5,5}
                        },5);
            var e2 = new Mino(new int[,]{
                            {0,5},
                            {5,5},
                            {5,0}
                        },5);

            var minos = new List<Mino> { a1, a2, b, c1, c2, c3, c4, d1, d2, d3, d4, e1, e2 };

            Box box = new Box(minos);

            box.Solve(1);
            box.DisplayAll();
        }

        class Mino
        {
            private int[,] mino;

            public Mino( int[,] mino, int pattern )
            {
                this.mino = mino;
                this.Pattern = pattern;
            }

            public int RowLength { get { return mino.GetLength(0); } }
            public int ColomnLength { get { return mino.GetLength(1); } }
            public int Pattern { get; private set; }
            public int GetValue(int row, int col)
            {
                return mino[row, col];
            }
        }

        class Box
        {
            private int[,] box = {
                           {0,0,0,0},
                           {0,0,0,0},
                           {0,0,0,0},
                           {0,0,0,0}
                       };
            private int RowLength { get { return box.GetLength(0); } }
            private int ColomnLength { get { return box.GetLength(1); } }
            private int GetValue(int row, int col)
            {
                return box[row, col];
            }
            private void SetValue(int row, int col, int value)
            {
                box[row, col] = value;
            }

            private List<Mino> minos;

            public Box(List<Mino> minos)
            {
                this.minos = minos;
            }

            private List<int[,]> boxes = new List<int[,]>();
            private int[] pattern = new int[4];
            private List<int[]> patterns = new List<int[]>();

            public void DisplayAll()
            {
                foreach (var b in boxes)
                {
                    for (int i = 0; i < RowLength; ++i)
                    {
                        for (int j = 0; j < ColomnLength; ++j)
                        {
                            Console.Write("{0}", b[i, j]);
                        }
                        Console.WriteLine();
                    }
                    Console.WriteLine();
                }

                foreach (var p in patterns)
                {
                    foreach (var i in p)
                    {
                        Console.Write(i);
                    }
                    Console.WriteLine();
                }

                Console.WriteLine("組み合わせ積み木のパターン数:{0}", patterns.Count);
                Console.WriteLine("重複のない詰め方の数:{0}", boxes.Count);
            }
            
            private void Record()
            {
                var pattern_sorted = pattern.Clone() as int[];
                Array.Sort<int>(pattern_sorted);

                if (!ExistPatternMino(pattern_sorted))
                {
                    patterns.Add(pattern_sorted);
                }

                if (!ExistPatternBox(box))
                {
                    boxes.Add(box.Clone() as int[,]);
                }
            }

            private bool ExistPatternMino(int[] pattern)
            {
                return patterns.Any( p => EqualArray( p, pattern ) );
            }

            private bool ExistPatternBox(int[,] box)
            {
                return boxes.Any(r => EqualBox(r, box)) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._90 ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._180 ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._270 ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._y ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._90y ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._180y ))) ||
                    boxes.Any(r => EqualBox(r, Rotate(box, Rotation._270y )));
            }

            private int[,] Rotate(int[,] box_s, Rotation rotation)
            {
                int[,] box_d = {
                           {0,0,0,0},
                           {0,0,0,0},
                           {0,0,0,0},
                           {0,0,0,0}
                       };
                
                switch (rotation)
                {
                    case Rotation._90:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[3 - j, i] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._180:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[3 - i, 3 - j] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._270:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[j, 3 - i] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._y:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[3 - i, j] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._90y:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[j, i] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._180y:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[i, 3 - j] = box_s[i, j];
                            }
                        }
                        break;
                    case Rotation._270y:
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                box_d[3 - j, 3 - i] = box_s[i, j];
                            }
                        }
                        break;
                }

                return box_d;
            }

            private enum Rotation
            {
                _90,
                _180,
                _270,
                _y,
                _90y,
                _180y,
                _270y
            }

            private bool EqualBox(int[,] lhs, int[,] rhs)
            {
                return Enumerable.Range(0, lhs.GetLength(0)).All(i =>
                    Enumerable.Range(0, lhs.GetLength(1)).All(j =>
                        lhs[i, j] == rhs[i, j]
                    ));
            }

            private bool EqualArray(int[] lhs, int[] rhs)
            {
                return Enumerable.Range(0, lhs.Length).All(i => lhs[i] == rhs[i]);
            }

            private bool CanPut(int row, int col, Mino mino)
            {
                if (row + mino.RowLength > RowLength ||    col + mino.ColomnLength > ColomnLength)
                {
                    return false;
                }

                return Enumerable.Range(0, mino.RowLength).Any(i =>
                    Enumerable.Range(0, mino.ColomnLength).Any(j =>
                        GetValue(row + i, col + j) != 0 && mino.GetValue(i, j) != 0)) ? false : true;
            }

            private void Put(int row, int col, Mino mino, int n)
            {
                for (int i = 0; i < mino.RowLength; i++)
                {
                    for (int j = 0; j < mino.ColomnLength; j++)
                    {
                        if (mino.GetValue(i, j) != 0)
                        {
                            SetValue(row+i, col+j, mino.GetValue(i, j));
                        }
                    }
                }
                pattern[n - 1] = mino.Pattern;
            }

            private void Remove(int row, int col, Mino mino)
            {
                for (int i = 0; i < mino.RowLength; i++)
                {
                    for (int j = 0; j < mino.ColomnLength; j++)
                    {
                        if (mino.GetValue(i, j) != 0)
                        {
                            SetValue(row+i, col+j, 0);
                        }
                    }
                }
            }

            public void Solve(int n)
            {
                for (int row = 0; row < RowLength; row++)
                {
                    if (CheckFilledRow(row))
                    {
                        continue;
                    }

                    for (int col = 0; col < ColomnLength; col++)
                    {
                        if (CheckFilledColomn(col))
                        {
                            continue;
                        }

                        foreach (var mino in minos)
                        {
                            if (CanPut(row, col, mino))
                            {
                                Put(row, col, mino, n);

                                if (n != 4)
                                {
                                    Solve(n + 1);
                                }
                                else
                                {
                                    Record();
                                }
                                Remove(row, col, mino);
                            }
                        }

                        if (GetValue(row, col) == 0)
                        {
                            return;
                        }
                    }
                }
            }

            private bool CheckFilledRow(int row)
            {
                return Enumerable.Range(0, ColomnLength).All(col => GetValue(row, col) != 0);
            }
            private bool CheckFilledColomn(int col)
            {
                return Enumerable.Range(0, RowLength).All(row => GetValue(row, col) != 0);
            }
        }
    }
}
回文日付 (Nested Flatten)

C#4.0です。日付判断用に標準のDatetimeを使用しました。計366個でした。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
    DateTime dummy;

    var list = from r in Enumerable.Range(1, 9999)
               let y = string.Format("{0:D4}", r)
               let m = string.Format("{0}{1}", y[3], y[2] )
               let d = string.Format("{0}{1}", y[1], y[0] )
               let ymd = string.Format("{0}/{1}/{2}", y,m,d)
               where DateTime.TryParse( ymd, out dummy )
               select ymd;

    foreach( var ymd in list )
    {
        Console.WriteLine(ymd);
    }
    Console.WriteLine(list.Count());
}
島の数をカウントする (Nested Flatten)
リンクリストを作って島を判別してます。
なるべく言語に依存しない感じに書こうとしたのですが、マップの解析とカウンター変数だけ.NETしてしまいました。
一次配列のループにしているので見辛くなっていたらすみません。
 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IslandCounter {
    class Program {
        static void Main() {
            string map =
@"□■□□
■□■□
□■■■
□□□□";

            int m = map.IndexOf(Environment.NewLine, 0);
            int n = map.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;

            map = string.Join(string.Empty, map.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
            int[] field = new int[m * n];

            Dictionary<char, int> counter = new Dictionary<char, int>();
            counter.Add('□', 0);
            counter.Add('■', 0);

            for (int i = 0; i < m * n; i++) {
                char c = map[i];
                counter[c]++;
                field[i] = i;
                if (i % m != 0) { // x軸の二行目から
                    int prev = i - 1;
                    if (c == map[prev]) {
                        field[i] = prev;
                        counter[c]--;
                    }
                }
                if (i >= m) { // y軸の二行目から
                    int prev = i - m;
                    if (c == map[prev] && GetParent(field, i) != GetParent(field, prev)) {
                        field[GetParent(field, i)] = prev;
                        counter[c]--;
                    }
                }
            }
            Console.WriteLine("白の島:" + counter['□'].ToString());
            Console.WriteLine("黒の島:" + counter['■'].ToString());
        }

        private static int GetParent(int[] field,int i) {
            int current = i;
            while (field[current] != current) {
                current = field[current];
            }
            return current;
        }
    }
}
居眠り床屋問題 (Nested Flatten)

それぞれの客にスレッドを割り当て、客が居なくなると本当にスレッドが止まるようにしてみました。

[11] 床屋、眠る [12] 来店 1 [11] 床屋、目覚める [11] 散髪開始 1 [13] 来店 2 [11] 散髪完了 1 [11] 散髪開始 2 [14] 来店 3 [15] 来店 4 [16] 来店 5 [16] 満席で立ち去る 5 [11] 散髪完了 2 [11] 散髪開始 4 [17] 来店 6 [18] 来店 7 [18] 満席で立ち去る 7 [19] 来店 8 [19] 満席で立ち去る 8 [11] 散髪完了 4 [11] 床屋、目覚める [11] 散髪開始 3 [11] 散髪完了 3 [11] 散髪開始 6 [11] 散髪完了 6 [11] 床屋、眠る [20] 来店 9 [11] 床屋、目覚める [11] 散髪開始 9 [21] 来店 10 [11] 散髪完了 9 [11] 散髪開始 10 [22] 来店 11 [23] 来店 12 [11] 散髪完了 10 [11] 散髪開始 12 [24] 来店 13 [25] 来店 14 [25] 満席で立ち去る 14 [26] 来店 15 [26] 満席で立ち去る 15 [27] 来店 16 [27] 満席で立ち去る 16 [11] 散髪完了 12 [11] 床屋、目覚める [11] 散髪開始 11 [11] 散髪完了 11 [11] 散髪開始 13 [11] 散髪完了 13 [11] 床屋、眠る ※ 16人のうち 10人を散髪

 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Linq;
using System.Threading;

class Program {
    static Random rnd = new Random();
    static int[] chair = new int[3];
    static int count;
    static bool end;
    static Thread owner;

    static void Main(string[] args) {
        owner = new Thread(Owner);
        Thread visitors = new Thread(Visitors);
        owner.Start(owner.ManagedThreadId);
        visitors.Start(new object[] { visitors.ManagedThreadId, 1 });
    }

    static void Owner(object threadID) {
        do {
            bool sleep;
            lock(chair) {
                sleep = chair.Sum() == 0;
                if(sleep && owner.ThreadState != ThreadState.Suspended) {
                    Console.WriteLine("[{0}] 床屋、眠る", threadID);
                }
            }

            //ここで満席になると店主が永遠の眠りについてしまうでしょう…

            if(sleep) {
                owner.Suspend();
            }

            Console.WriteLine("[{0}] 床屋、目覚める", threadID);

            if(!ownerSleep) {
                for(int i = 0; i < chair.Length; i++) {
                    if(chair[i] != 0) {
                        Console.WriteLine("[{0}] 散髪開始 {1}", threadID, chair[i]);
                        Thread.Sleep(rnd.Next(100, 401));
                        Console.WriteLine("[{0}] 散髪完了 {1}", threadID, chair[i]);
                        count++;
                        chair[i] = 0;
                    }
                }
            }
        } while(chair.Sum() != 0 || !end);

        Console.WriteLine("[{0}] 床屋、眠る", threadID);
        Console.WriteLine("※ 16人のうち {0}人を散髪", count);
        Console.ReadLine();
    }

    static void Visitors(object threadID_i) {
        int threadID, i;
        threadID = (int)(((object[])threadID_i)[0]);
        i = (int)(((object[])threadID_i)[1]);

        if(i == 9) {
            Thread.Sleep(1200);
        } else {
            Thread.Sleep(rnd.Next(0, 201));
        }

        Console.WriteLine("[{0}] 来店 {1}", threadID, i);
        bool packed = true;

        for(int j = 0; j < chair.Length; j++) {
            lock(chair) {
                if(chair[j] == 0) {
                    chair[j] = i;
                    if(owner.ThreadState == ThreadState.Suspended) {
                        owner.Resume();
                    }
                    packed = false;
                    break;
                }
            }
        }

        if(packed) {
            Console.WriteLine("[{0}] 満席で立ち去る {1}", threadID, i);
        }

        if(i < 16) {
            Thread visivor = new Thread(Visitors);
            visivor.Start(new object[] { visivor.ManagedThreadId, ++i });
        } else {
            end = true;
        }
    }
}
【1回目】
[11] 床屋、眠る
[12] 来店 1
[11] 床屋、目覚める
[11] 散髪開始 1
[12] 来店 2
[12] 来店 3
[11] 散髪完了 1
[11] 散髪開始 2
[12] 来店 4
[12] 来店 5
[12] 満席で立ち去る 5
[11] 散髪完了 2
[11] 散髪開始 3
[12] 来店 6
[12] 来店 7
[12] 満席で立ち去る 7
[11] 散髪完了 3
[11] 散髪開始 4
[12] 来店 8
[11] 散髪完了 4
[11] 散髪開始 6
[11] 散髪完了 6
[11] 散髪開始 8
[11] 散髪完了 8
[11] 床屋、眠る
[12] 来店 9
[11] 床屋、目覚める
[11] 散髪開始 9
[12] 来店 10
[12] 来店 11
[12] 来店 12
[12] 満席で立ち去る 12
[11] 散髪完了 9
[11] 散髪開始 10
[12] 来店 13
[12] 来店 14
[12] 満席で立ち去る 14
[11] 散髪完了 10
[11] 散髪開始 11
[12] 来店 15
[11] 散髪完了 11
[11] 散髪開始 13
[12] 来店 16
[11] 散髪完了 13
[11] 散髪開始 15
[11] 散髪完了 15
[11] 散髪開始 16
[11] 散髪完了 16
[11] 床屋、眠る
※ 16人のうち 12人を散髪

【2回目】
[12] 床屋、眠る
[13] 来店 1
[12] 床屋、目覚める
[12] 散髪開始 1
[13] 来店 2
[13] 来店 3
[13] 来店 4
[13] 満席で立ち去る 4
[12] 散髪完了 1
[12] 散髪開始 2
[13] 来店 5
[12] 散髪完了 2
[12] 散髪開始 3
[13] 来店 6
[13] 来店 7
[13] 満席で立ち去る 7
[13] 来店 8
[13] 満席で立ち去る 8
[12] 散髪完了 3
[12] 散髪開始 5
[12] 散髪完了 5
[12] 散髪開始 6
[12] 散髪完了 6
[12] 床屋、眠る
[13] 来店 9
[12] 床屋、目覚める
[12] 散髪開始 9
[13] 来店 10
[13] 来店 11
[13] 来店 12
[13] 満席で立ち去る 12
[12] 散髪完了 9
[12] 散髪開始 10
[13] 来店 13
[13] 来店 14
[13] 満席で立ち去る 14
[12] 散髪完了 10
[12] 散髪開始 11
[13] 来店 15
[13] 来店 16
[13] 満席で立ち去る 16
[12] 散髪完了 11
[12] 散髪開始 13
[12] 散髪完了 13
[12] 散髪開始 15
[12] 散髪完了 15
[12] 床屋、眠る
※ 16人のうち 10人を散髪

【3回目】
[12] 床屋、眠る
[13] 来店 1
[12] 床屋、目覚める
[12] 散髪開始 1
[13] 来店 2
[12] 散髪完了 1
[12] 散髪開始 2
[13] 来店 3
[13] 来店 4
[12] 散髪完了 2
[12] 散髪開始 4
[13] 来店 5
[13] 来店 6
[13] 満席で立ち去る 6
[13] 来店 7
[13] 満席で立ち去る 7
[13] 来店 8
[13] 満席で立ち去る 8
[12] 散髪完了 4
[12] 散髪開始 3
[12] 散髪完了 3
[12] 散髪開始 5
[12] 散髪完了 5
[12] 床屋、眠る
[13] 来店 9
[12] 床屋、目覚める
[12] 散髪開始 9
[13] 来店 10
[13] 来店 11
[13] 来店 12
[13] 満席で立ち去る 12
[13] 来店 13
[13] 満席で立ち去る 13
[12] 散髪完了 9
[12] 散髪開始 10
[13] 来店 14
[13] 来店 15
[13] 満席で立ち去る 15
[13] 来店 16
[13] 満席で立ち去る 16
[12] 散髪完了 10
[12] 散髪開始 11
[12] 散髪完了 11
[12] 散髪開始 14
[12] 散髪完了 14
[12] 床屋、眠る
※ 16人のうち 9人を散髪
 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
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Linq;
using System.Threading;

class Program {
    static Random rnd = new Random();
    static int[] chair = new int[3];
    static int count;
    static bool ownerSleep;
    static bool end;

    static void Main(string[] args) {
        Thread owner = new Thread(Owner);
        Thread visitors = new Thread(Visitors);
        owner.Start(owner.ManagedThreadId);
        visitors.Start(visitors.ManagedThreadId);
    }

    static void Owner(object threadID) {
        do {
            lock(chair) {
                if(chair.Sum() == 0) {
                    if(!ownerSleep) {
                        ownerSleep = true;
                        Console.WriteLine("[{0}] 床屋、眠る", threadID);
                    }
                } else {
                    if(ownerSleep) {
                        ownerSleep = false;
                        Console.WriteLine("[{0}] 床屋、目覚める", threadID);
                    }
                }
            }

            if(!ownerSleep) {
                for(int i = 0; i < chair.Length; i++) {
                    if(chair[i] != 0) {
                        Console.WriteLine("[{0}] 散髪開始 {1}", threadID, chair[i]);
                        Thread.Sleep(rnd.Next(100, 401));
                        Console.WriteLine("[{0}] 散髪完了 {1}", threadID, chair[i]);
                        count++;
                        chair[i] = 0;
                    }
                }
            }
        } while(chair.Sum() != 0 || !end);

        Console.WriteLine("[{0}] 床屋、眠る", threadID);
        Console.WriteLine("※ 16人のうち {0}人を散髪", count);
        Console.ReadLine();
    }

    static void Visitors(object threadID) {
        for(int i = 1; i <= 16; i++) {
            Console.WriteLine("[{0}] 来店 {1}", threadID, i);
            bool packed = true;

            lock(chair) {
                for(int j = 0; j < chair.Length; j++) {
                    if(chair[j] == 0) {
                        chair[j] = i;
                        packed = false;
                        break;
                    }
                }
            }

            if(packed) {
                Console.WriteLine("[{0}] 満席で立ち去る {1}", threadID, i);
            }

            if(i == 8) {
                Thread.Sleep(1200);
            } else {
                Thread.Sleep(rnd.Next(0, 201));
            }
        }

        end = true;
    }
}
シードを固定した乱数 (Nested Flatten)
Visual Stuido 2008以降のテスティングフレームワークを使用。
値の確認をする程度なら、テスティングフレームワーク+SequenceEqual使えば目視の必要なんぞナッシング。
 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
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Collections.Generic;

namespace TestProject1
{
    [TestClass()]
    public class FilterContextTest
    {
        [TestMethod()]
        public void RandomTest01()
        {
            int seed = 33;
            for (int i = 0; i < 13; i++)
            {
                var ary1 = CreateRandomArray(seed);
                var ary2 = CreateRandomArray(seed);
                Assert.IsTrue(ary1.SequenceEqual(ary2));
            }
        }

        public IEnumerable<int> CreateRandomArray(int seed)
        {
            Random rand = new Random(seed);
            return Enumerable.Range(1, 20).Select(num => rand.Next(num));
        }
    }
    //(中略)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
using System;
class P
{
    static void Main()
    {
        Random rand = new Random(32);
        for (int i = 0; i< 10; i++)
                Console.WriteLine(rand.Next());
    }
}
Twitterへの投稿 (Nested Flatten)

LINQ to Twitterを使用

http://www.codeplex.com/LinqToTwitter

C#でLINQ to XXXが使用できるなら、利用しない手は無いでしょう。お題は投稿までですが、ユーザ名一覧の取得もやってみました。

 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
using System;
using System.Linq;
using System.Net;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using System.Threading;
using System.Globalization;

namespace ConsoleApplication
{
    using LinqToTwitter;

    class Program
    {
        static void Main(string[] args)
        {
            string userName = "ユーザ名";
            string password = "パスワード";

            var twitterCtx = new TwitterContext(userName, password);
            twitterCtx.UpdateStatus("投稿メッセージ");
            
            //ユーザ名一覧を取得
            twitterCtx.User.ToList().ForEach( user => Console.WriteLine(user.ScreenName) );

            Console.ReadKey();
        }
    }
}
いちばん長いしりとり (Nested Flatten)

とりあえずの愚直実装。 350語くらいなら一瞬ででるんですが、 その先はぜんぜん終わる気配がないです。

 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Word
{
    public string Tango{get;set;}
    public bool Used{get;set;}

    public Word(string t)
    {
        Tango = t;
        Used = false;
    }

    public char First()
    {
        return Tango.First();
    }

    public char Last()
    {
        return Tango.Last();
    }
}

class Program
{
    static Dictionary<char, List<Word>> wordDic = new Dictionary<char, List<Word>>();
    static List<Word> wordList = new List<Word>();
    static int count = 0;
    static int maxcount = 0;

    static void Add(Word word)
    {
        List<Word> list;

        if (wordDic.ContainsKey(word.First()))
        {
            list = wordDic[word.First()];
        }
        else
        {
            list = new List<Word>();
            wordDic[word.First()] = list;
        }

        list.Add(word);
    }

    static void Main(string[] args)
    {
        using (StreamReader sr = new StreamReader("D:\\tango.txt"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Word w = new Word(line);
                Add(w);
                wordList.Add(w);
            }
        }

        foreach (Word word in wordList)
        {
            Shiritori(word);
        }

        Console.WriteLine("Finish");
        Console.Read();
    }

    private static void Shiritori(Word word)
    {
        word.Used = true;
        ++count;

        if (wordDic.ContainsKey(word.Last()))
        {
            foreach (Word t2 in wordDic[word.Last()])
            {
                if (t2.Used == false)
                {
                    Shiritori(t2);
                }
            }
        }

        SetCount(count);
        --count;
        word.Used = false;
    }

    private static void SetCount(int count)
    {
        if (maxcount < count)
        {
            maxcount = count;
            Console.WriteLine(maxcount);
        }
    }
}
Twitterへの投稿 (Nested Flatten)
こんな感じで。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
using System.Net;
using System.Text;
using System.Web;

class ついった {
    static void Main(string[] args) {
        using(WebClient client = new WebClient()) {
            client.Encoding = Encoding.UTF8;
            client.Credentials = new NetworkCredential("ID", "Pass");
            string query = "http://twitter.com/statuses/update.xml?status=" + 
                HttpUtility.UrlEncode("どう書く?orgなう");
            client.UploadData(query, System.Text.Encoding.Default.GetBytes(""));
        }
    }
}
メソッドのフック (Nested Flatten)
VB.NETに移す前の元のC#のコードも一応投稿しておくことにします。そういえば、VB.NETは戻り値のないラムダ式が書けないので、メソッドにするしかなかったのでした。
 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.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;

interface IHoge
{
    void Piyo();
}

public class BeforeAfterProxy<T> : RealProxy
{
    public BeforeAfterProxy(T obj, Action before, Action after)
        : base(typeof(T))
    {
        this.obj = obj;
        this.before = before;
        this.after = after;
    }

    public override IMessage Invoke(IMessage msg)
    {
        var mm = (IMethodMessage)msg;
        before();
        mm.MethodBase.Invoke(obj, mm.Args);
        after();
        return new ReturnMessage(
            null, null, 0, mm.LogicalCallContext, (IMethodCallMessage)msg);
    }

    private T obj;
    private Action before;
    private Action after;
}

class HogeImpl : IHoge
{
    public void Piyo() {Console.WriteLine("piyo");}

    static void Main()
    {
        var hoge = new HogeImpl();
        var xHoge = new BeforeAfterProxy<IHoge>(hoge,
            () => Console.WriteLine("Before"),
            () => Console.WriteLine("After"));

        var tHoge = (IHoge)xHoge.GetTransparentProxy();
        tHoge.Piyo();
    }
}
ラングトンのアリの描画 (Nested Flatten)

アリ1匹につき1スレッドで。

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;

namespace doukaku276
{
    class Program
    {
        const int ANT_NUM = 10;
        const int FIELD_WIDTH = 100;
        const int FIELD_HEIGHT = 100;
        static Random rnd = new Random();

        static void Main(string[] args)
        {
            new FormMain().ShowDialog();
        }

        class Ant
        {
            int x, y;
            int direction;//0:↑ 1:→ 2:↓ 3:←
            Color color;
            public Ant()
            {
                x = rnd.Next(FIELD_WIDTH);
                y = rnd.Next(FIELD_HEIGHT);
                direction = rnd.Next(4);
                color = Color.FromArgb(rnd.Next(254), rnd.Next(255), rnd.Next(255));
            }
            public void step(Bitmap bmp)
            {
                bool b = bmp.GetPixel(x, y).R != 255; // 黒? R=255を白とする
                direction = (direction + (b ? 1 : 3)) % 4; // 回転
                bmp.SetPixel(x, y, b ? Color.White : color); // 色反転
                // 前進
                switch (direction)
                {
                case 0: y--; break;
                case 1: x++; break;
                case 2: y++; break;
                case 3: x--; break;
                }
                if (x < 0) x += FIELD_WIDTH;
                if (x >= FIELD_WIDTH) x -= FIELD_WIDTH;
                if (y < 0) y += FIELD_HEIGHT;
                if (y >= FIELD_HEIGHT) y -= FIELD_HEIGHT;
            }
        }
        class FormMain : Form
        {
            Bitmap bmp = new Bitmap(FIELD_WIDTH, FIELD_HEIGHT);
            List<Thread> ants = new List<Thread>();
            public FormMain()
            {
                lock (bmp)
                {
                    for (int y = 0; y < FIELD_HEIGHT; y++)
                        for (int x = 0; x < FIELD_WIDTH; x++)
                            bmp.SetPixel(x, y, Color.White);
                }
                this.Size = new Size(FIELD_WIDTH * 3 + 100, FIELD_HEIGHT * 3 + 100);
                this.CenterToScreen();
                this.DoubleBuffered = true;
            }
            void update()
            {
                Ant ant = new Ant();
                while (true)
                {
                    lock (bmp)
                    {
                        ant.step(bmp);
                    }
                    this.Invalidate();
                    Thread.Sleep(1);
                }
            }
            protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
            {
                foreach(var t in ants) t.Abort();
            }
            protected override void OnPaint(PaintEventArgs e)
            {
                //base.OnPaint(e);
                Graphics g = e.Graphics;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                lock (bmp)
                {
                    g.DrawImage(bmp, 30, 30, FIELD_WIDTH * 3, FIELD_HEIGHT * 3);
                }
                g.DrawString(string.Format("ants:{0}", ants.Count), this.Font, Brushes.Black, 40, FIELD_HEIGHT * 3);
            }
            protected override void OnClick(EventArgs e)
            {
                var thread = new Thread(new ThreadStart(update));
                thread.Start();
                ants.Add(thread);
            }
        }
    }
}

C#でビットマップにごりごり描画します。 フレームスキップして速度を稼いでいます。

今回一番はまったのは、Color.FromArgb(255, 0, 0, 0) が Color.Black とイコールではないってこと。ColorはARGB以外の情報を持っているので、ToArgb()で比較するように、とMSDNにある。

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace LangtonsAnt {
    class Ant {
        Point pos;
        int direction;
        public int X { get { return pos.X; } }
        public int Y { get { return pos.Y; } }

        public Ant(int x, int y) {
            pos.X = x;
            pos.Y = y;
            direction = 0;
        }
        public void Advance(bool IsBlack) {
            if (IsBlack) {
                direction = (direction + 1) % 4;
            } else {
                direction = (direction + 3) % 4;
            }
            switch (direction) {
                case 0: pos.Y--; break; //北
                case 1: pos.X++; break; //東
                case 2: pos.Y++; break; //南
                case 3: pos.X--; break; //西
            }
        }
    }
    class Form1 : Form {
        Bitmap bitmap;                  //世界=ビットマップ
        List<Ant> ants;                 //アリたち
        Timer timer;                    //タイマー
        long step_count;                //ステップ数
        Color Black = Color.FromArgb(255, 0, 0, 0);
        Color White = Color.FromArgb(255, 255, 255, 255);
        public Form1() {
            //マップの初期化
            this.Width = 300; this.Height = 200;
            bitmap = new Bitmap(300, 200, Graphics.FromHwnd(this.Handle));
            //100,100を中心に黒点を打つ
            Random r = new Random();
            for (int i = 0 ; i < 100 ; i++) {
                int x = r.Next(40) + bitmap.Width / 2 - 20;
                int y = r.Next(40) + bitmap.Height / 2 - 20;
                bitmap.SetPixel(x, y, Black);
            }
            //アリの初期化
            ants = new List<Ant>();
            ants.Add(new Ant(r.Next(20) + bitmap.Width / 2 - 10, r.Next(20) + bitmap.Height / 2 - 10));
            ants.Add(new Ant(r.Next(20) + bitmap.Width / 2 - 10, r.Next(20) + bitmap.Height / 2 - 10));
            ants.Add(new Ant(r.Next(20) + bitmap.Width / 2 - 10, r.Next(20) + bitmap.Height / 2 - 10));
            //タイマー初期化
            step_count = 0;
            timer = new Timer();
            timer.Interval = 300;       //300msに1度再描画
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        void timer_Tick(object sender, EventArgs e) {
            //高速化のため1描画につき150周回す
            for (int step = 0 ; step < 150 ; step++) {
                foreach (Ant ant in ants) {
                    int x = (ant.X + bitmap.Width) % bitmap.Width;
                    if (x < 0) x += bitmap.Width;
                    int y = (ant.Y + bitmap.Height) % bitmap.Height;
                    if (y < 0) y += bitmap.Height;
                    Color color = bitmap.GetPixel(x, y);
                    if (color == Black) {
                        ant.Advance(true);
                        bitmap.SetPixel(x, y, White);
                    } else {
                        ant.Advance(false);
                        bitmap.SetPixel(x, y, Black);
                    }
                }
            }
            Refresh();
            step_count += 150;
            Text = step_count.ToString();
        }
        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);
            e.Graphics.DrawImage(bitmap, ClientRectangle);
        }
        protected override void OnClosed(EventArgs e) {
            timer.Stop(); timer = null;
            base.OnClosed(e);
        }
    }
    static class Program {
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
バイナリクロック (Nested Flatten)
LINQを使ってワンライナー的な処理を書いてみました。「Select( binary =>」の部分まで一行にしてしまうと、かえって読みにくくなると判断したのでこの程度で。
 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
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new DateTime(2009, 7, 8, 20, 18, 0));
        Console.WriteLine(BinaryClock.Convert(new DateTime(2009, 7, 8, 20, 18, 0)));
        Console.ReadLine();
    }
}

public class BinaryClock
{
    public static string Convert(DateTime dateTime)
    {
        return string.Join(Environment.NewLine, new int[] { dateTime.Hour, dateTime.Minute }
            .Select(num => System.Convert.ToString(num, 2)).Select(binary =>
            {
                return new string(binary.ToCharArray().Select(c => c == '0' ? '□' : '■').ToArray()).PadLeft(6, ' ');
            }).ToArray());
    }
}


//2009/07/08 20:18:00
// ■□■□□
// ■□□■□

結構素直な方法と思います。

 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
    class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            byte hours = (byte)now.Hour;
            byte minutes = (byte)now.Minute;
            StringBuilder uh = new StringBuilder();
            StringBuilder lh = new StringBuilder();
            StringBuilder um = new StringBuilder();
            StringBuilder lm = new StringBuilder();
            for (byte i = 0; i < 8; i++)
            {
                byte mask = (byte)(1 << (7 - i));
                if ((hours & mask) != 0)
                {
                    uh.Append("■");
                    lh.Append("□");
                }
                else
                {
                    uh.Append("□");
                    lh.Append("■");
                }
                if ((minutes & mask) != 0)
                {
                    um.Append("■");
                    lm.Append("□");
                }
                else
                {
                    um.Append("□");
                    lm.Append("■");
                }
            }
            Console.Write(uh);
            Console.WriteLine(um);
            Console.Write(lh);
            Console.WriteLine(lm);
            Console.WriteLine(now);
        }
next >>

Index

Feed

Other

Link

Pathtraq

loading...