ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Simplifying code using array (https://www.excelbanter.com/excel-programming/285426-simplifying-code-using-array.html)

John Pierce

Simplifying code using array
 
Is there a way to say that MyArray(5) cannot equal any element of the
array, without listing each element, as below?
Do
MyArray(5) = Int(10 * Rnd)
Loop Until MyArray(5) < MyArray(4) And _
MyArray(5) < MyArray(3) And _
MyArray(5) < MyArray(2) And _
MyArray(5) < MyArray(1)

Tom Ogilvy

Simplifying code using array
 
Sub Tester13()
Dim myArray(1 To 10)
For i = 1 To 10
Do
temp = Int(10 * Rnd + 1)
bMatch = False
For j = 1 To i - 1
If myArray(j) = temp Then
bMatch = True
Exit For
End If
Next
Loop While bMatch
myArray(i) = temp
sStr = sStr & "myarray(" & i & ")= " & myArray(i) & vbNewline
Next
msgbox sStr
End Sub


--
Regards,
Tom Ogilvy




John Pierce wrote in message
om...
Is there a way to say that MyArray(5) cannot equal any element of the
array, without listing each element, as below?
Do
MyArray(5) = Int(10 * Rnd)
Loop Until MyArray(5) < MyArray(4) And _
MyArray(5) < MyArray(3) And _
MyArray(5) < MyArray(2) And _
MyArray(5) < MyArray(1)




Colo[_23_]

Simplifying code using array
 
Hi John,
I assume you would like to make an unique number list in array...
The random number value sequence not overlapping is generated by
shuffling the arrangement which put in order the value which can
usually be taken.


Code:
--------------------

Sub TestShuffleArrayAsRandom()
Const n As Long = 5
Dim MyArray() As Long
Dim i As Long
Dim r As Long
Dim tmp

ReDim MyArray(0 To n)

'Make a sample MyArrayay
For i = 0 To n
MyArray(i) = i
Next

'Shuffle Array
For i = 1 To n
r = Int(Rnd() * n) + 1
tmp = MyArray(i): MyArray(i) = MyArray(r): MyArray(r) = tmp
Next
Stop 'Pls take a look at MyArray

End Sub

--------------------



---
Message posted from http://www.ExcelForum.com/


Colo[_24_]

Simplifying code using array
 
Sorry, I found a little mistake. Please modify my code as follows.

Code:
--------------------

'Shuffle Array
For i = 0 To n

--------------------



---
Message posted from http://www.ExcelForum.com/



All times are GMT +1. The time now is 11:27 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com