配列要素数と同じ数のランダムな数値が代入された配列を作成する

注意:
この文書は以前「.NETでいきまっしょい!」で公開していたものですが、公開以降メンテナンスされていません。 今や古い情報となった内容が記載されている場合があるのでご注意ください。
VB.NET
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
Public Shared Function MakeRandomizedArray(ByVal length As Integer) As Integer()

    Dim i As Integer
    Dim j As Integer
    Dim rnd As New System.Random()
    Dim blnIsUsed As Boolean
    Dim intRandom As Integer
    Dim arr(length - 1) As Integer

    For i = 0 To length - 1

        Do

            intRandom = rnd.Next(0, length)

            blnIsUsed = False

            For j = 0 To i - 1

                If intRandom = arr(j) Then

                    blnIsUsed = True

                    Exit For

                End If

            Next j

        Loop While blnIsUsed

        arr(i) = intRandom

    Next i

    Return arr

End Function
C#
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
public static int[] MakeRandomizedArray( int length )
{
    int iRandom;
    int[] arr = new int[length];
    bool bIsUsed;
    System.Random rnd = new System.Random();

    for ( int i = 0; i < length; i++ )
    {
        do
        {
            iRandom = rnd.Next( 0, length );

            bIsUsed = false;

            for ( int j = 0; j < i; j++ )
            {
                if ( iRandom == arr[j] )
                {
                    bIsUsed = true;
                    break;
                }
            }
        } while ( bIsUsed );

        arr[i] = iRandom;
    }

    return arr;
}
出力例
arr(0) = 7
arr(1) = 9
arr(2) = 8
arr(3) = 1
arr(4) = 0
arr(5) = 4
arr(6) = 2
arr(7) = 5
arr(8) = 6
arr(9) = 3
Press any key to continue

 オーディオプレイヤーのシャッフル再生などに使うような、ランダムな順番を作成するための関数。 見ての通り、配列の添え字の範囲のランダムな数値が配列の各要素に代入されて返される。 たいしたアルゴリズムを使っているわけではないので、もしかしたら改良の余地があるかもしれない。