2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C#] 配列をシャッフルする方法

Last updated at Posted at 2018-06-03

#配列の要素をシャッフルしたい
配列の要素をシャッフルして試験したいときありませんか?
自分はありました。
そのときに使ったプログラムをメモします。

using System;
using System.Linq;

namespace random
{
    class Program
    {
        static void Main(string[] args)
        {
            /// <summary>
            /// 試行パターン番号配列の基本配列
            /// </summary>
            //int[] basicArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
            int[] basicArray = Enumerable.Range(1, 20).Select(n => (int)n).ToArray();
            /// <summary>
            /// 試行パターン番号配列
            /// 試行パターン番号配列の基本データの要素の順番をシャッフルした結果
            /// </summary>
            int[] trialPatternArray = basicArray.OrderBy(i => System.Guid.NewGuid()).ToArray();

            // コンソールに出力
            foreach (int element in trialPatternArray)
            {
                System.Console.WriteLine(element);
            }
            Console.ReadKey();
        }
    }
}

実行結果は以下の通り。

3
11
15
1
20
18
19
12
16
6
2
14
17
13
5
4
10
8
9
7

これで配列要素をシャッフルできます。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?