Suppose N is the length of your array, what you really want is a permutation of the first N positive integers, do the following:

Copy Code

1- Fill the array such that a(i) = i 2- for i = 1 to n do j = random(n) swap(a(i),a(j))

See more:

Random Number that be not repeat

VB

Copy Code

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

Comments

And your question is?

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:

Suppose N is the length of your array, what you really want is a permutation of the first N positive integers, do the following:

Copy Code

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

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