查找列表中的差最接近的人数较多,最近的较低的数字

时间:2019-02-01 01:31:05

标签: c# list numbers difference closest

我有一个int列表,我想从给定的referenceNumber中找到与最接近的较低数字的差和与最接近的较高数字的差。 因此,在这种情况下,如果referenceNumber为5。它怎么能输出最近的lowerNumber = 1和最近的highestNumber = 3?

List<int> Test = new List<int>() {2, 1, 4, 8 };

        int referenceNumber = 5;
        int closestLowerNumber;
        int closestHigherNumber;

/ * closestLowerNumber是差到最接近的较低的数字(1) 最近的数字是最接近的更高数字(3)* /

4 个答案:

答案 0 :(得分:2)

尽管这可以在LINQ中完成,但这并不是解决此任务的最有效方法。我会选择这样的东西:

int referenceNumber = 5;
int? closestLowerNumber = null;
int? closestHigherNumber = null;

foreach (var i in Test)
{
    if (i < referenceNumber)
    {
        if (!closestLowerNumber.HasValue || closestLowerNumber < i)
        {
            closestLowerNumber = i;
        }
    }
    else if (i > referenceNumber)
    {
        if (!closestHigherNumber.HasValue || closestHigherNumber > i)
        {
            closestHigherNumber = i;
        }
    }
}

Console.WriteLine(
    $"{referenceNumber}:{referenceNumber - closestLowerNumber}:{closestHigherNumber - referenceNumber}");

答案 1 :(得分:2)

您可以执行以下操作。

file = open("numbers.txt", "r") #read the file
file = file.read().splitlines() #create a list where each value is a line of the file
file = list(map(int, file)) #convert each of the values on the list to "int"
print(sum(file)) #sum all the values inside the list

另一个选择

var closestLower = Test.Where(x=>x<referenceNum).Min(x=>referenceNum-x);
var closestHigher = Test.Where(x=>x>referenceNum).Min(x=>x-referenceNum);

输出 最下面的:1 最近的最高值:3

答案 2 :(得分:1)

这可能是一种半有效的方式(根据数据,不进行排序可能会更有效):

var test = new List<int>() { 2, 1, 4, 8 };
int referenceNumber = 5;
int closestLowerNumber = 0;
int closestHigherNumber = 0;

foreach (var val in test.OrderBy(v => v))
{
    if (val < referenceNumber)
    {
        closestLowerNumber = val;
    }
    else if (val > referenceNumber)
    {
        closestHigherNumber = val;
        break;
    }
}

Console.WriteLine(string.Format("Closest low: {0}, Closest high: {1}, Distance low: {2}, Distance high: {3}", closestLowerNumber, closestHigherNumber, (referenceNumber - closestLowerNumber), (closestHigherNumber - referenceNumber)));

输出:

Closest low: 4, Closest high: 8, Distance low: 1, Distance high: 3

Try it online

请注意,这是假定至少小1个数字和大1个数字。如果不是这种情况,closestLowerNumberclosestHigherNumber将保持为0并给出奇怪的结果。因此,最好改为使用可为null的int,以便您可以使用int? closestLowerNumber检查是否已设置(closestLowerNumber.HasValue)。

答案 3 :(得分:0)

基本上是基里尔的答案,但更干净:

var Test = new List<int>() { 2, 1, 4, 8 };
var reference = 5;

var closestLower = int.MinValue;
var closestHigher = int.MaxValue;

foreach (var value in Test) {
    switch (value.CompareTo(reference)) {
        case -1: // value < reference
            closestLower = Math.Max(closestLower, value);
            break;
        case 0: // value == reference
            break;
        case 1: // value > reference
            closestHigher = Math.Min(closestHigher, value);
            break;
    }
}