I just wanted to know if there's anything built into the .net framework where I can easily return the delta between two numbers? I wrote code that does this but it sounds like something that should be in the framework already. Thanks.
-Bryan
I just wanted to know if there's anything built into the .net framework where I can easily return the delta between two numbers? I wrote code that does this but it sounds like something that should be in the framework already. Thanks.
-Bryan
I'm under the impression that "delta" is the difference between two numbers.
Until you tell me differently, I think what you want is:
delta = Math.Abs(a - b);
What is the delta of two numbers? Delta has a certain meaning in set-theory and infinitesimal calculus, but this doesn't refer to numbers!
If you want to calculate the difference between two numbers a and b, you write |a - b|
which is Math.
Abs
(a - b)
in C#.
public static int Delta(int a, int b)
{
int delta = 0;
if (a == b)
{
return 0;
}
else if (a < b)
{
while (a < b)
{
a++;
delta++;
}
return delta;
}
else
{
while (b < a)
{
b++;
delta++;
}
return delta;
}
}
:p
Oh boy, I hope no (future) employer comes across this and stops reading in disgust before he reaches the end of this post..
public static int Delta(int a, int b)
{
return a > 0? Delta(a-1, b-1) : a < 0 ? Delta(a+1, b+1) : b > 0 ? b : -b;
}
I think that's even better than @JulianR Delta implementation :-p
Edit: I didn't realize that this was already suggested by @Robert Harvey, credit to him ;-)
I decided to revise JulianR's funny answer above.
The code is shorter, but perhaps more tricky:
public static int Delta(int a, int b)
{
int delta = 0;
while (a < b)
{
++a;
++delta;
}
while (b < a)
{
++b;
++delta;
}
return delta;
}
(for the humor-impaired.... this is no more serious than the bizarre question that started the thread)
The Linq version (requires CLR 4.0).
(cracks fingers, clears throat)
var delta = (from t in Enumerable.Range(a, a).Zip(Enumerable.Range(b, b))
select Math.Abs(t.Item1 - t.Item2))
.First();