View Single Post
  #3  
Old 07-10-2009, 04:26 AM
Phil_V Phil_V is offline
Valued Forum Contributor
 
Join Date: 23 Feb 2006
Location: Near London, England
MS Office Version:Office 2003
Posts: 752
Phil_V is attaining expert status Phil_V is attaining expert status
Re: Create a random array contain a fixed number

I don't know if the placement of the '2' has to be random with the array, but if so the above code will not do it.
Below is a flexible solution that will prompt you for inputs, (most are defaulted to the values in your original post).
Hopefully you will be able to see how it works, but if not feel free to ask questions:

Code:
Sub random_arrays_with_fix()
Dim thearray() As Long
Dim input_reply As Variant
Dim upper_bound As Long, fixed_num As Long, array_elements As Long, qty_of_arrays As Long
Dim counter As Long, arr_index As Long

' Clear the worksheet first
ActiveSheet.Cells.ClearContents

' Get the highest value allowed for the array
Do
    input_reply = InputBox("Enter the highest value that can be in the array", "Highest value", "100")
    If input_reply = "" Then Exit Sub Else upper_bound = input_reply
Loop While Not IsNumeric(upper_bound) Or upper_bound < 1

' Get the 'fixed' value for the array
Do
    input_reply = InputBox("Enter the 'fixed' number:", "Fixed Number", "2")
    If input_reply = "" Then Exit Sub Else fixed_num = input_reply
Loop While (Not IsNumeric(fixed_num)) Or fixed_num > upper_bound
  
' How many elements in the array?
Do
    input_reply = InputBox("How many elements are required in the array:", "Number of elements", "4")
    If input_reply = "" Then Exit Sub Else array_elements = input_reply
Loop While Not IsNumeric(array_elements) Or array_elements < 1
  
' How many arrays to generate?
Do
    input_reply = InputBox("How many arrays should be generated?", "Quantity of Arrays", "5")
    If input_reply = "" Then Exit Sub Else qty_of_arrays = input_reply
Loop While Not IsNumeric(qty_of_arrays) Or qty_of_arrays < 1

' Generate the arrays
ReDim thearray(array_elements - 1)
For counter = 1 To qty_of_arrays
    ' Fill it with random numbers
    For arr_index = 0 To UBound(thearray)
        thearray(arr_index) = Int(Rnd() * upper_bound)
    Next
    thearray(Int(Rnd() * (array_elements - 1))) = fixed_num
    ' Paste the array into a row on the worksheet
    Range("A" & counter).Resize(columnsize:=UBound(thearray) + 1) = thearray
Next

End Sub
__________________
If you find the response helpful please click the scales in the blue bar above and rate it
If you don't like the response, don't bother with the scales, they are not for you
Reply With Quote