I’m interested in speed, not good looking code, that is why I’m using array and not list(of integer).
I have an array looking like: 0,1,0,1,1,0,1,0,1,1,1,0,0,1
I’m interesting in the position of each number so I can later pick one randomly.
so what I do is looping through the array to take position number of each 1 then creating a new array looking like this: 2,4,5,7,9,10,11,14
is bitwise could be used here? I have no idea
code look like:
Private Function theThing() As Integer() Dim x As Integer 'arIn() would be a parameter Dim arIn() As Integer = {0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1} Dim ar() As Integer = Nothing Dim arCount As Integer = -1 For x = 1 To arIn.GetUpperBound(0) If arIn(x) = 1 Then arCount += 1 End If Next If arCount > -1 Then 'using redim preseve is slower than the loop above ReDim ar(arCount) arCount = 0 For x = 1 To arIn.GetUpperBound(0) If arIn(x) = 1 Then ar(arCount) = x arCount += 1 End If Next End If Return ar End Function
* EDIT *
current solution(10% to 15% faster) is now
Private Function theThing() As Integer Dim ar() As Integer = {0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1} Dim arLenght As Integer = ar.GetUpperBound(0) Dim arCount As Integer = 0 Dim x As Integer For x = 1 To arLenght If ar(x) = 1 Then ar(arCount) = x arCount += 1 End If Next dim r As New Random() Return ar(r.Next(arCount)) End Function
I don’t think it can be optimized more than that, unless someone find a way to do exactly what the solution does but way faster
Before this question, my whole thing was able to do about 25500 run each 10 seconds.
Now, it can do over 32250 all the time, a 21% increase, thanks!
Few tips on the original algorithm:
If arCount > -1is always going to be true. Remove it.If you wish to keep the same inputs/outputs, then I don’t think there is much else that can be improved.
Now if you wanted a function that does the random selection too, then it might be a bit better. I’ll write in C# since I know it better. You should be able to understand:
I’m afraid it won’t get any better than that. Not unless you can somehow change the inputs/outputs or requirements.