Mike
Mike

Reputation: 151

If there a faster/better optimized way to check if value's in range made of another value?

my friend and I were wondering today if we can optimize a part of code. I couldn't find anything similiar, I mean there are ways of doing it but it's kinda different what we have and it's never about optimization and range also changes. So the current code is:

if (((this.TempMingraph + skok) < Convert.ToInt32(datalegend[0])) ||
   ((this.TempMingraph - skok) > Convert.ToInt32(datalegend[0])))
       this.TempMingraph = Convert.ToInt32(datalegend[0]);

if (((this.TempMaxgraph + skok) < Convert.ToInt32(datalegend[1])) ||
   ((this.TempMaxgraph - skok) > Convert.ToInt32(datalegend[1])))
       this.TempMaxgraph = Convert.ToInt32(datalegend[1]);

if (this.ScaleVoltageFlag)
{
    ActualThread_ChartAxesScaleMinMax(chart, TempMingraph - skok, TempMaxgraph + skok);

Explanation: we have two values from "outside", we can only convert them to INT32 since we need to work on values instead of strings, those values are datalegend[0] and datalegend[1]. Values are integers always and in range of few thousands and never equals to 0.

Our helper values are: TempMingraph and TempMaxgraph. WE need to check exactly the same things on both of them but using different values: for TempMingraph we have to use outside value of datalegend[0] and for TempMaxgraph we have to use outside value of datalegend[1].

So each "Temp" value which are always integers, are a "base" for a range to check. Let's take TempMingraph so the range to check is from TempMingraph - skok (skok equals int = 10) to TempMingraph + skok. We need to check if datalegend[0] is within that range. If not, TempMingraph = datalegend[0], that's easy. And then exactly the same for TempMaxgraph but comparing to datalegend[1]. Constant skok remains the same. Last if is not important, just sets new values. Is that the best/fastest way to do that? If not, how would you solve it?

Upvotes: 0

Views: 48

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Here is how I would probably do it - Since both conditions are repeating, I would move them to a method. Also, they are much simpler once you deal with only int values and remove all the unnecessary brackets:

this.TempMingraph = CalculateGraphValue(this.TempMingraph, skok, Convert.ToInt32(datalegend[0]));
this.TempMaxgraph = CalculateGraphValue(this.TempMingraph, skok, Convert.ToInt32(datalegend[1]));


private int CalculateGraphValue(int graph, int skok, int datalegend)
{
    return (graph + skok < datalegend || graph - skok > datalegend) ? datalegend : graph;
}

The method simply returns the value of either datalegend or graph, depending on the values of graph, skok and datalegend.

Upvotes: 1

Related Questions