Click here to Skip to main content
15,070,089 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
Random Number that be not repeat
VB
dim a(12) as string
dim n as intger
dim r as new random
dim f as boolean = False

        For i = 1 To 12
            n = r.Next(12) + 1
             TextBox1.Text = CStr(n)
            a(i) = CStr(n)
            For j = 1 To i - 1
                While f = False
                    n = r.Next(12) + 1
                    If n = CStr(a(j)) Then
                        a(i) = CStr(n)
                    Else
                        f = True
                    End If
                End While
            Next
        Next
Posted
Comments
OriginalGriff 24-Nov-10 15:33pm
   
And your question is?

1 solution

I'm not really sure about what you wanna do? So maybe you can be a little more explicit. However, If you are trying to generate a random array where elements cannot be repeated here is a good algorithm.

Suppose N is the length of your array, what you really want is a permutation of the first N positive integers, do the following:
1- Fill the array such that a(i) = i
2- for i = 1 to n do
       j = random(n)
       swap(a(i),a(j))
   
v2
Comments
Manfred Rudolf Bihy 24-Nov-10 18:52pm
   
Nice one, take my five for that, but in your solution there is still the restriction that the possible numbers run from 1 to n. His question aims more into the direction to choose random integers and repeat if an integer was already chosen. But that's only the way I read it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900