vendredi 13 octobre 2017

How to create an array with a random order of integers from 0 to n-1 [duplicate]

I've got a function in my VB code that's supposed to create a length n array with the numbers 0 to (n-1) exactly once in a random order.

My strategy was to get a random number in my range, see if it's already in the array, if it is, get a new one, if it isn't put it in the next index of the array.

Here's what I've got:

Private Function GenRandOrder(n As Integer) As Integer()
    'init vars
    Dim result(n - 1) As Integer 'array size n
    Dim rand As Integer 'holds random integers from 0 to n-1

    'fill array with numbers outside of range
    For Each number As Integer In result
        number = -1
    Next

    'add a random number
    For Each number As Integer In result
        rand = rnd.Next(0, n) 'get random number from 0 to n-1
        ' ***** TEST CODE *******
        System.Diagnostics.Debug.WriteLine(CStr(rand)) 'Prints rand
        ' ***** END TEST ********
        While (ArrayContains(result, rand)) 'if it's already in the array
            rand = rnd.Next(0, n) 'get a new rand from 0 to n-1
            ' ***** TEST CODE *******
            System.Diagnostics.Debug.WriteLine(CStr(rand)) 'Prints rand
            ' ***** END TEST ********
        End While
        number = rand 'add new random to the array
    Next
    ' ***** TEST CODE *******
    System.Diagnostics.Debug.WriteLine(String.Join(" ", result)) 'Prints array
    ' ***** END TEST ********
    Return result
End Function

Private Function ArrayContains(array As Integer(), num As Integer) As Boolean
    For Each number As Integer In array
        If (number = num) Then
            Return True
        End If
    Next
    Return False
End Function

Where rnd is an instance of the Random() default class.

here's a sample output for n = 2:

1

0

1

0 0

no matter what happens, the code creates an n sized array of all zeros.

1) What is going on?

2) Is there a simpler way to fill my array




Aucun commentaire:

Enregistrer un commentaire