Single Tread Array Iteration

Juwar

Member
Joined
Jun 13, 2005
Messages
8
Programming Experience
1-3
Does anyone know how to do a single tread iteration.

For example I have the following array: ("dog", "cat", "mouse", "bird")
I need to go through the array in such a way that it picks up each object once through the first run and then return to the beginning again and pick up the first two.

Let's say I need 6 objects returned. The result should therefore be:

dog
cat
mouse
bird
dog
cat...

Or if I need just 5 objects returned, the result set would be

dog
cat
mouse
bird
dog

I tried to put a loop within a loop but that just returns the entire set multiple times. This is not what I want exactly.

I want it to go through the entire array. When it reaches the last object in the array, I want it to go back to the first object and continue through.

Does anyone have any ideas?

Thanks, any help would be appreciated.
 
Here are two suggested methods, both uses the Mod operator for calculation. This first calculates how many full copies of source array is needed, and how many additional items, then AddRange and Add these.
VB.NET:
Dim itemsNeeded As Integer = 10
Dim list() As String = {"A", "B", "C"}
Dim copies As Integer = itemsNeeded \ list.Length
Dim remainder As Integer = itemsNeeded Mod list.Length
Dim newlist As New List(Of String)
newlist.Capacity = itemsNeeded
For i As Integer = 1 To copies
    newlist.AddRange(list)
Next
For i As Integer = 0 To remainder - 1
    newlist.Add(list(i))
Next
This second just loops array adding one by one until count is reached.
VB.NET:
Dim itemsNeeded As Integer = 10
Dim list() As String = {"A", "B", "C"}
Dim counter As Integer = 0
Dim newlist As New List(Of String)
newlist.Capacity = itemsNeeded
Do Until counter = itemsNeeded
    Dim index As Integer = counter Mod list.Length
    newlist.Add(list(index))
    counter += 1
Loop
The latter method is surprisingly significantly faster, but this is only noticable for 10000 items and more.
 
Back
Top