Decimal Comparison

  • Thread starter Thread starter Typpo
  • Start date Start date
T

Typpo

Hi,

I have an ArrayList of decimals, and I want to figure out which two are
the closest (least difference) from one another. I know I can loop
through the decimals, but this is very tedious and some people have told
me there are easier ways.

Here is an example -
ArrayList contains:
1.12
1.15
2.45
2.44

2.44 and 2.45 have the least difference between them. Is there any easy
way to do this?

Thanks.
 
I know of no easier way. You have to have two nested loops that will
compare each decimal with each other one, and keep track of the pair
with the (currently) smallest difference.
 
I know of no easier way. You have to have two nested loops that will
compare each decimal with each other one, and keep track of the pair
with the (currently) smallest difference.
If the list is sorted one loop is enough.
 
True. You need two nested loops if the list is not guaranteed to be
sorted. If it is guaranteed to be sorted, you need only one pass
through the list. Here is the unsorted
version:

int firstIndex = -1;
int secondIndex = -1;
decimal diff = Decimal.MaxValue;
for (int i = 0; i < list.Count - 1; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
decimal newDiff = Math.Abs(list - list[j]);
if (newDiff < diff)
{
diff = newDiff;
firstIndex = i;
secondIndex = j;
}
}
}
if (firstIndex < 0)
{
... there were 0 or 1 elements in the list ... nothing to compare
}
else
{
... the smallest difference was between values at index firstIndex
and index secondIndex, and the difference was "diff".
}
 
Back
Top