Searching for a suitable algorithm

Hello,

I’ve got something to analyze today. Given is a value “MyValue”, on the basis of which a value “Difference” should be calculated.
Does anyone recognize a pattern, an algorithm, from my manual Select…Case…query? What could this algorithm look like without having to specify a single case for all areas?

[code]Select Case MyValue
Case 3
Difference = 0.5
Case 4
Difference = 0.75

// Following results: Steps 2
Case 5 To 6
Difference = 1
Case 7 To 8
Difference = 1.25

// Following results: Steps 5
Case 9 To 13
Difference = 2
Case 14 To 18
Difference = 3
Case 19 To 23
Difference = 4
Case 24 To 28
Difference = 5
Case 29 To 33
Difference = 6
Case 34 To 38
Difference = 7

// Following results: Steps 4
Case 39 To 42
Difference = 8
Case 43 To 46
Difference = 9
Case 47 To 50
Difference = 10
// And so on…
End Select[/code]

A large array of preset differences with an index myValue would find the difference in one step.

Dim diff() As Double = Array(0,0,0, 0.5, 0.75, 1, 1, 1.25, 1.25, 2, 2, 2, 2, 2, ...) Dim theDiff As Double = diff(MyValue)

Thanks Rick for your suggestion. I’ve reworked my code. So it returns the same results without having to create an extra case for each area.

[code]Dim diff, start As Double

Select Case MyValue
Case 3
diff = 0.5

Case 4 To 8
start = 0.5

For i As Integer = 5 To MyValue Step 2
start = start + 0.25
Next

diff = start + 0.25

Else
start = 3

For i As Integer = 9 To MyValue Step 5
start = start + 1
Next

diff = start - 2

End Select[/code]

Your first method returns 9, 10, 10 to MyValues 43,47,48. Your second slower method returns 8, 9, 9.

Yes, I’ve modified the different value factor. Is it much slower than the first method?

Yes. Higher MyValues = more iterations (loop).

You can translate your second effort as pure math as:

[code] Dim diff As Double
Dim delta As Integer

Select Case MyValue

Case Is < 3
diff = 0

Case 3
diff = 0.5

Case 4 To 8

delta = (MyValue-5)/2+1
diff = 0.75 + (delta * 0.25)

Case Is > 8

delta = (MyValue-9)/5+2
diff = delta

End Select

Return diff[/code]