Convert integer hashset to a integer array - arrays

So i have made a hashset with -you've guessed it- integers in it. Now i need to convert this into a array, so i can refer to each array 'cell' and use the value from the hashset in a process.
Currently i add to the hashset like so:
While NumbersToRemember.Count < 1
RandomNumber = Random.Next(2, 6)
If NumbersToRemember.Add(RandomNumber) then ...
i have tried using NumbersToRemember.ToArray() but it hasnt been working as expected.
Any advice?
Note: See comment by JerryM for the solution.

There is not even a complete loop shown, so it is hard to tell what might be happening. it outputs only zeros in comments indicates something else might be wrong. Test:
Dim hs As New HashSet(Of Int32)
Dim temp As Int32
For n As Int32 = 1 To 10
temp = rng.Next(2, 16)
If hs.Contains(temp) = False Then
hs.Add(temp)
End If
Next
Dim nums = hs.ToArray
Console.WriteLine("Vals: {0}", String.Join(", ", hs.ToArray()))
Console.WriteLine("Nums: {0}", String.Join(", ", nums))
Output:
Vals: 2, 7, 14, 11, 12, 10
Nums: 2, 7, 14, 11, 12, 10
It is hard to tell what you are trying to do, but to get a small set of random values in a given range, this seems a bit simpler:
Dim count As Int32 = 6
Dim randvals = Enumerable.Range(2, 16).
OrderBy(Function(x) Rnd.Next()).
Take(count).ToArray()
Console.WriteLine("Rand Vals: {0}", String.Join(", ", randvals))
Rand Vals: 2, 13, 8, 6, 3, 12

Related

How to find out if an arithmetic sequence exists in an array

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.

Update no of values starting with index in an byte array

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...

Best way to insert an element into an ordered array in Scala

I have an Array, or Seq looks like
val myArray = collection.mutable.ArrayBuffer[Int](1,4,8,10,12,13)
val newElem = 7
I want to insert the new element into the Array at the right position, so that the array is still ordered.
I don't want to generate a new array here.
My solution is to find the insert position first, and then insert it.
def findInsertPosition(myArray: collection.multable.ArrayBuffer[Int], newElem: Int): Int
then call
myArray.insert(pos, newElem)
The question is how to write the findInsertPosition function in Scala style, without using while, for loops?
or if you have better solution?
Find the insert position with lastIndexWhere and add one to it then insert at that position.
scala> val xs = scala.collection.mutable.ArrayBuffer(1,4,8,10,12,13)
xs: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 4, 8, 10, 12, 13)
scala> xs.insert(xs.lastIndexWhere(_ < 7) + 1, 7)
scala> xs
res10: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 4, 7, 8, 10, 12, 13)
This might be a bit inefficient, but it works:
def findInsertPosition(myArray: collection.mutable.ArrayBuffer[Int], newElem: Int): Int =
myArray.takeWhile(_ < newElem).size
It will be the correct index when inserting.
Find the correct index point and insert.
val idx = myArray.indexWhere(_>newElem)
myArray.insert(if (idx<0) myArray.length else idx, newElem)
// ArrayBuffer(1, 4, 7, 8, 10, 12, 13)
The first thing that comes to my mind:
myArray.insert(
Stream.range(0, myArray.length)
.find(a(_) >= newElem)
.getOrElse(myArray.length),
newElem)
another approach would be something similar to Brian's answer
myArray.insert(
myArray.indexWhere(_ >= newElem),
newElem)

VB.NET Get Keys by sorted Values in Hashtable

I am studying VB.NET and I want to know better idea to get Keys by sorted values in Hashtable
Here is my solution that I built
Dim int_Value As Integer() = New Integer() {-9, 2, 8, 6, 8, 1, -9}
Dim int_Key As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7}
Dim Dum_Int(int_Key.Length) As Integer
Dim STORE_KEYS As New ArrayList
Array.Copy(int_Value, Dum_Int, Dum_Int.Length - 1)
Array.Sort(Dum_Int)
Array.Reverse(Dum_Int)
For I = 0 To Dum_Int.Length - 1
For II = 0 To int_Value.Length - 1
If Dum_Int(I) = int_Value(II) Then
STORE_KEYS.Add(int_Key(II))
int_Value(II) = Integer.MaxValue
End If
Next
Next
I got output like..
'' OUTPUT''
(0) 3 {Integer} Object
(1) 5 {Integer} Object
(2) 4 {Integer} Object
(3) 2 {Integer} Object
(4) 6 {Integer} Object
(5) 1 {Integer} Object
(6) 7 {Integer} Object
I assume that I have Hashtable.
I create two arrays and store both Keys (int_Key) and Values(Int_Value) From Hashtable
then I copy Value(Int_Value) array to Dum_Int to sort values
Whenever I found matching int value between Sorted Array and Original Value Array
I stored in to STORE_KEYS(arraylist) and I insert Max Int value to original array to prevent overlapping issue.
However, is there any way to improve this method ?
I don't believe that better sorting algor can't help to simplify this method.
Can you provide any hints to simplify this method?
thanks
The Array.Sort method has an overload that will sort an array based on another array:
Dim keys = myHastable.Keys.Cast(Of Integer)().ToArray()
Dim values = myHastable.Values.Cast(Of Integer)().ToArray()
Array.Sort(values, keys)

Creating arrays in QTP

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.

Resources