I am trying to create an array of integers in QTP ( the ints are 9, 16, 25,34,43). I think the code to instantiate it should be (but I could be wrong since I have never created an array in QTP before),
Dim pages(5)
pages(0) = 9
pages(1) = 16
...
Then I have a for loop with a variable that goes from 1 to 50 and based off of the value of the variable it does one thing and if the variable is one of the values in the array it does something else. For that I have,
For g = 1 to 50
if g<> 9 and g<> 16 and g<> 25 and g<>34 and g<> 43 Then
DoCoolStuff...
else
DoBoringStuff...
End If
Next
My question is, is there a command that will allow me to replace that ugly if statement with something like
if g <> in pages*?
If you want a Dimensioned Array, then that is the only way to declare an array. If you wanted a Non dimensioned array you then can use,
Dim pages()
pages = Array(9, 16, 25, 34, 43)
However, you can also do this,
Dim pages()
ReDim pages(5)
pages = Array(9, 16, 25, 34, 43)
Coming to your problem, you can get this going by using the Filter function. Although there is a very small problem. Filter method takes in String, so even with that function your will match 1, 2, 3, 4, 5, 6 along with the real/actual values 9, 16, 25, 34, 43.
As,
1 occurs in 16.
2 occurs in 25.
3 occurs in 34 and 43.
4occurs in 34 and 43.
5 occurs in 25.
6 occurs in 16.
It still thinks they occur in the String. One way to get around this is to Format the numbers as a two literal. Something like.
Dim pages(), g As Integer
ReDim pages(5)
pages = Array("09", "16", "25", "34", "43")
For g = 1 To 50
If UBound(Filter(pages, Format(g, "00"))) > -1 Then
'Do Cool Stuff here
Else
'Do Boring Stuff here
End If
Next
EDIT :
The other way is to create a User Defined Function that could Loop through your Array and find if the Value is Found in your Array. Something like,
Public Function FindArrayElement(SearchArray As Variant, LookupValue As Integer) As Boolean
Dim aCtr As Integer
For aCtr = 0 To UBound(SearchArray)
If CLng(SearchArray(aCtr)) = LookupValue Then
FindArrayElement = True
Exit Function
End If
Next
FindArrayElement = False
End Function
The function takes in two Arguments. The first is the Array in which the values are defined, the second is the Value looked up for. So your Original code would change to.
Dim pages(), g As Integer
ReDim pages(5)
pages = Array(9, 16, 25, 34, 43)
For g = 1 To 50
If FindArrayElement(pages, g) Then
'Do Cool Stuff here
Else
'Do Boring Stuff here
End If
Next
First, I, too, would suggest to initialize Pages like this:
Dim Pages(): Pages=(9,16,25,34,43)
Second, and independently from the first aspect, you could use this code to check if g is contained in Pages:
Dim Elem
Dim Found: Found=false
For Each Elem in Pages
If Elem = g then
Found=true
Exit For
End If
End For
If Found then
DoBoringStuff
else
DoCoolStuff
End If
The For..Each loop iterates as many times as there are elements in the Pages array. For each iteration, Elem is set to one Pages array element.
Note that the comparison is between Integers, as requested.
Related
If there is an array that contains random integers in ascending order, how can I tell if this array contains a arithmetic sequence (length>3) with the common differece x?
Example:
Input: Array=[1,2,4,5,8,10,17,19,20,23,30,36,40,50]
x=10
Output: True
Explanation of the Example: the array contains [10,20,30,40,50], which is a arithmetic sequence (length=5) with the common differece 10.
Thanks!
I apologize that I have not try any code to solve this since I have no clue yet.
After reading the answers, I tried it in python.
Here are my codes:
df = [1,10,11,20,21,30,40]
i=0
common_differene=10
df_len=len(df)
for position_1 in range(df_len):
for position_2 in range(df_len):
if df[position_1] + common_differene == df[position_2]:
position_1=position_2
i=i+1
print(i)
However, it returns 9 instead of 4.
Is there anyway to prevent the repetitive counting in one sequence [10,20,30,40] and also prevent accumulating i from other sequences [1,11,21]?
You can solve your problem by using 2 loops, one to run through every element and the other one to check if the element is currentElement+x, if you find one that does, you can continue form there.
With the added rule of the sequence being more than 2 elements long, I have recreated your problem in FREE BASIC:
DIM array(13) As Integer = {1, 2, 4, 5, 8, 10, 17, 19, 20, 23, 30, 36, 40, 50}
DIM x as Integer = 10
DIM arithmeticArrayMinLength as Integer = 3
DIM index as Integer = 0
FOR position As Integer = LBound(array) To UBound(array)
FOR position2 As Integer = LBound(array) To UBound(array)
IF (array(position) + x = array(position2)) THEN
position = position2
index = index + 1
END IF
NEXT
NEXT
IF (index <= arithmeticArrayMinLength) THEN
PRINT false
ELSE
PRINT true
END IF
Hope it helps
Edit:
After reviewing your edit, I have come up with a solution in Python that returns all arithmetic sequences, keeping the order of the list:
def arithmeticSequence(A,n):
SubSequence=[]
ArithmeticSequences=[]
#Create array of pairs from array A
for index,item in enumerate(A[:-1]):
for index2,item2 in enumerate(A[index+1:]):
SubSequence.append([item,item2])
#finding arithmetic sequences
for index,pair in enumerate(SubSequence):
if (pair[1] - pair[0] == n):
found = [pair[0],pair[1]]
for index2,pair2 in enumerate(SubSequence[index+1:]):
if (pair2[0]==found[-1] and pair2[1]-pair2[0]==n):
found.append(pair2[1])
if (len(found)>2): ArithmeticSequences.append(found)
return ArithmeticSequences
df = [1,10,11,20,21,30,40]
common_differene=10
arseq=arithmeticSequence(df,common_differene)
print(arseq)
Output: [[1, 11, 21], [10, 20, 30, 40], [20, 30, 40]]
This is how you can get all the arithmetic sequences out of df for you to do whatever you want with them.
Now, if you want to remove the sub-sequences of already existing arithmetic sequences, you can try running it through:
def distinct(A):
DistinctArithmeticSequences = A
for index,item in enumerate(A):
for index2,item2 in enumerate([x for x in A if x != item]):
if (set(item2) <= set(item)):
DistinctArithmeticSequences.remove(item2)
return DistinctArithmeticSequences
darseq=distinct(arseq)
print(darseq)
Output: [[1, 11, 21], [10, 20, 30, 40]]
Note: Not gonna lie, this was fun figuring out!
Try from 1: check the presence of 11, 21, 31... (you can stop immediately)
Try from 2: check the presence of 12, 22, 32... (you can stop immediately)
Try from 4: check the presence of 14, 24, 34... (you can stop immediately)
...
Try from 10: check the presence of 20, 30, 40... (bingo !)
You can use linear searches, but for a large array, a hash map will be better. If you can stop as soon as you have found a sequence of length > 3, this procedure takes linear time.
Scan the list increasingly and for every element v, check if the element v + 10 is present and draw a link between them. This search can be done in linear time as a modified merge operation.
E.g. from 1, search 11; you can stop at 17; from 2, search 12; you can stop at 17; ... ; from 8, search 18; you can stop at 19...
Now you have a graph, the connected components of which form arithmetic sequences. You can traverse the array in search of a long sequence (or a longest), also in linear time.
In the given example, the only links are 10->-20->-30->-40->-50.
Hey everyone: I'm trying to make a function that digs through an array and adds values from range2 when the corresponding value from range1 equals criteria1.
I'm relatively new to VBA, so it's not the most elegant function in the world, but here's my code:
Function SingleArray(range1 As Range, range2 As Range, criteria1 As String)
Dim newrange() As Double
Dim d As Integer
Dim g As Integer
Dim i As Integer
g = Application.WorksheetFunction.CountIf(range1, criteria1)
ReDim newrange(g)
d = 1
For i = 0 To (range1.Count)
If range1(i) = criteria1 Then
newrange(d) = range2.Item(i).Value
d = d + 1
End If
Next i
SingleArray = newrange
End Function
Here is my data sample:
range2 range1
-5000 Bob
-5000 Jim
200 Bob
500 Jim
5000 Bob
200 Bob
300 Bob
1000 Bob
When I set the criteria as "Bob," the array that is returned is as follows:
{0,-5000,200,5000,200,300,1000}
I'm genuinely at a loss for how that zero is making it in there. Any thoughts you can provide would be most welcome!
1-D arrays default to a zero-based index structure (e.g. 0, 1, 2, 3, ....). You are looping through the ranges with a one based index (e.g. 1, 2, 3, 4, ...).
When you declare ReDim newrange(5) you are actually creating an array with six elements, not five (e.g. 0, 1, 2, 3, 4, 5)
You can make all arrays on that code sheet default to a one based index by putting this compiler directive at the top of the code sheet.
Option Base 1
You can also change the way the array is declared on the fly by specifying the Lower Boundary and the Upper Boundary.
ReDim newrange(1 to g)
I have a byte array of, let's say, of 100 bytes.
from 0 to 15, these bytes correspond to parameter1,
from 16 to 50, corresponds to parameter2,
from 51 to 80 corresponds to parameter3,
from 81 to 99 corresponds to parameter4
Indexes 1,15,16,50,51,80,81,99 are not fixed. They vary with the parameter
I read the bytes from a device. I have to update, for example, bytes for parameter 3.
How can I accomplish that?
Thank you
P.S. Below is a simple example. I replaced the bytes "23" and "34" with "99"
Dim temp As Byte() = New Byte() {12, 23, 12, 23, 34, 56, 67, 89}
Dim tempReplaced As Byte() = New Byte() {12, 23, 12, 99, 99, 56, 67, 89}
The Array.Copy method will copy a specified set of elements from one array to another.
The following statement will do what you want.
Array.Copy(dataArray, parm3Index, parm3Array, 0, parm3Array.Length)
Where
dataArray is the data you read from the device
parm3Index is the index of parameter3 in the array
parm3Array is an array containing the bytes that you want to change parameter3 to
Until now I have found this:
Public Shared Sub ReplaceByteArray(ByRef sourceArray As Byte(), arrayToReplace As Byte(), startPosition As Integer, length As Integer)
Dim counter As Integer = 0
While counter < length
sourceArray(startPosition + counter) = arrayToReplace(counter)
counter += 1
End While
End Sub
Silly me, I thought it was more complicated
If you find another solution more efficient or better, feel free to post it...
I have 6 arrays of data as longs. I want to find a way to graph all six arrays as separate lines on a Chart Control.
I have created the Chart object, in my Series Collection Editor I have 6 members, but I cannot find a function that does something along the lines of chart1.series1.setData(myArray).
I know I can go through and call .add() on every point, but I am wondering if there is a direct way to assign an array to a Series.
There is no built in way to add a whole range apart from databinding. You can call, as you said, the AddXY method of the Points property (or one of the related methods in the type DataPointCollection) of the Series, like so:
'Add data from Array1 to the first series of the chart
Chart.Series(0).Points.Clear() 'Clear all points
For i = 0 to Array1.Count - 1
Chart.Series(0).Points.AddXY(i, Array1(i)) 'Adds the data from the array to the first series
Next
If you have the data in a multidimensional (e.g. Dim Data()() As Long) you can do something like
For a = 0 to Data.Count - 1
Chart.Series(a).Points.Clear() 'Clear all points from the ath series
For i = 0 to Data(a).Count - 1
Chart.Series(a).Points.AddXY(i, Data(a)(i)) 'Adds the data from the ath array to the ath series
Next
Next
Note the X values will be just an index (0 to the array's count - 1) since you provided no further information.
Or you could write an extension method in a new Module
Public Module Extensions
<System.Runtime.CompilerServices.Extension>
Public Sub AddRange(d As System.Windows.Forms.DataVisualization.Charting.DataPointCollection, data() As Long)
Dim meCount As Integer = d.Count
For i = 0 To data.Count - 1
d.AddXY(meCount + i, data(i))
Next
End Sub
End Module
Now you can just call the AddRange method for the Points property of the series:
Chart.Series(0).Points.AddRange(Array1)
You can do it by adding point by point as Jens mentions, and this works find. Another way which should work fine is:
For a as integer = 0 to AmountOfSeries.count - 1 step 1
Chart1.Series(a).Points.DataBindXY(ArrayX1, ArrayY1)
Next
This may be closer to what you were looking for - a way to set two arrays to a series.
Here's what it would look like with only one series:
Dim xs As Double() = {0, 1, 2, 3, 4}
Dim ys As Double() = {0, 1, 2, 3, 4}
Chart1.Series(0).Points.DataBindXY(xs, ys)
How can I find out the number of dimensions in an array in Classic ASP ( VBScript ) .
I am being passed an Array with multiple dimensions but I only want to look at the last. Seems easy in other languages.
Ubound(MySingleDimensionalArray, 2) ' Number of Array Elements
Ubound(MyMultiDimensionalArray, 1) ' Number of Columns
Ubound(MyMultiDimensionalArray, 2) ' Number of Rows
Similar approach to feihtthief's answer here as I assume this is what you want rather than the size of a specified dimension.
Function NumDimensions(arr)
Dim dimensions : dimensions = 0
On Error Resume Next
Do While Err.number = 0
dimensions = dimensions + 1
UBound arr, dimensions
Loop
On Error Goto 0
NumDimensions = dimensions - 1
End Function
Then calling it as so:
Dim test(9, 5, 4, 3, 9, 1, 3, 5)
NumDimensions(test)
will give you the value 8
It's a bit crappy but it'll do what you asked.
function ArrayDimensions( theArray )
dim Result,test
Result = 0
if isarray(theArray) then
on error resume next
do
test = -2
test = ubound(theArray,result+1)
if test > -2 then result = result + 1
loop until test=-2
on error goto 0
end if
ArrayDimensions = Result
end function