0

I have a for loop that is working as intended. I iterate over an array of values and replace bad values (-99999) with the closest good value (if the bad value is on either end of the array) or the average of the two surrounding values (if the bad value is in the middle of the array). However, these nested loops smelled to me and I am looking for any suggested means of optimizing this (in terms of readability or performance).

I could access or remove the bad values using Dim badValues = MeasuredValues.Where(Function(x) x = -99999) but I'm not sure how I can keep track of the indexes for calculating the replacement value when using .Where. I'm no vb.net expert.

      For index = 0 To MeasuredValues.Count - 1
        If MeasuredValues(index) = -99999 Then
            Dim nextGoodValue = -99999
            Dim previousGoodValue = -99999
            Dim replacementValue = -99999
            For j = index To MeasuredValues.Count - 1
                If MeasuredValues(j) <> -99999 Then
                    nextGoodValue = MeasuredValues(j)
                    Exit For
                End If
            Next
            For k = index To 0 Step -1
                If MeasuredValues(k) <> -99999 Then
                    previousGoodValue = MeasuredValues(k)
                    Exit For
                End If
            Next
            If previousGoodValue = -99999 Then
                replacementValue = nextGoodValue
            ElseIf nextGoodValue = -99999 Then
                replacementValue = previousGoodValue
            Else
                replacementValue = (nextGoodValue + previousGoodValue) / 2
            End If
            MeasuredValues(index) = replacementValue
        End If
    Next

Thanks for your time, please let me know if you need more info or have any questions.

user95227
  • 1,533
  • 1
  • 16
  • 34
  • 2
    You can have it as fast as it is, or you can use some other code which will be slower, so your two hoped-for optimisations are at odds. [Is a LINQ statement faster than a 'foreach' loop?](https://stackoverflow.com/q/3156059/1115360) and [In .NET, which loop runs faster, 'for' or 'foreach'?](https://stackoverflow.com/q/365615/1115360). Adding a comment or two to the code to make it really obvious what is going on could be the best way to increase readability/maintainability. – Andrew Morton Dec 26 '19 at 19:55
  • I'm voting to close this question as off-topic because it is working code so it belongs on [Code Review](https://codereview.stackexchange.com/). They might even spot some optimisations to the code as it is. – Andrew Morton Dec 26 '19 at 19:59
  • @AndrewMorton thanks, I was unaware of Code Review at the time of writing. I also agree that with a couple of quick comments this code block is quite clear – user95227 Jan 03 '20 at 20:09

0 Answers0