Найти порядковый номер числа из последовательности наиболее близкое к числу заданному пользователем - C#
Формулировка задачи:
Дана последовательность длиной до 100 вещественных чисел. Найти порядковый номер того из них,которое наиболее близко к числу заданному пользователем.
Решение задачи: «Найти порядковый номер числа из последовательности наиболее близкое к числу заданному пользователем»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClosestNumber
{
class Program
{
static void Main(string[] args)
{
decimal[] array = new decimal[5] { 80.23M, 80.40M, 80.80M, 80.00M, 20.45M };
decimal TargetNumber = 70.40M;
var result = FindClosestIndex(TargetNumber, array, (target, element) => Math.Abs(target - element)); //Optionally add in a "(distance) => distance == 0" at the end to enable early termination.
Console.WriteLine(result);
}
public static int FindClosestIndex<T, U>(T target, IEnumerable<T> elements, Func<T, T, U> distanceCalculator, Func<U, bool> earlyTermination = null) where U : IComparable<U>
{
U minDistance = default(U);
int minIndex = -1;
using (var enumerator = elements.GetEnumerator())
for (int i = 0; enumerator.MoveNext(); i++)
{
var distance = distanceCalculator(enumerator.Current, target);
if (minIndex == -1 || minDistance.CompareTo(distance) > 0)
{
minDistance = distance;
minIndex = i;
}
if (earlyTermination != null && earlyTermination(minDistance))
break;
}
return minIndex;
}
}
}