简体   繁体   English

在数组或列表中查找数字对

[英]Find pairs of numbers in an array or List

My goal is to find pairs of numbers in an array or List. 我的目标是在数组或列表中找到数字对。 A pair in this case is defined by the maximum difference between two entries. 在这种情况下,一对是由两个条目之间的最大差异定义的。 For instance 例如

1
50
2
100
102
800

Pairs(if max difference threshold is 2) with line numbers(array number): 与行号(数组号)配对(如果最大差异阈值为2):

1,2 line number of 1 is 0
100,101 line number of 100 is 3

How do I do this? 我该怎么做呢?

相反,这里没有库,您可以对数组进行排序,然后在循环中自动查找对。

I don't know of any library that would help you with this. 我不知道有什么图书馆可以帮助您。 You can use the methods in the framework. 您可以使用框架中的方法。

For the case where threshold is 1, if you put the numbers from the array in a hash set you can efficiently look up the numbers that is a part of a pair: 对于阈值为1的情况,如果将数组中的数字放入散列集中,则可以有效地查找成对的数字:

HashSet<int> set = new HashSet<int>(myArray);
int[] pairs = myArray.Where(i => set.Contains(i + 1)).ToArray();

The pairs array will have the lower number of the pairs, eg { 1, 100 } when the pairs are 1, 2 and 100, 101 . pairs数组将具有较少的对,例如{ 1, 100 }当对分别为1, 2100, 101时, { 1, 100 }

To get the index instead of the number, iterate the indexes instead: 要获取索引而不是数字,请迭代索引:

HashSet<int> set = new HashSet<int>(myArray);
int[] index = Enumerable.Range(myArray.Length).Where(i => set.Contains(myArray[i + 1])).ToArray();

The index array will have the index of the lower numbers of the pairs. index数组将具有对中较小数字的索引。

You can use LINQ to do this: 您可以使用LINQ来做到这一点:

var numbers = new[]
{
    1,
    50,
    2,
    100,
    102,
    800
};

var treshold = 2;

var numWithIndexes = numbers.Select((value, index) => new { value, index });

var pairs = from num1 in numWithIndexes
            from num2 in numWithIndexes
            where (num2.value - num1.value <= treshold) && (num2.value - num1.value > 0)
            select new[]
        {
            num1.value, // first number in the pair
            num2.value, // second number in the pair
            num1.index, // index of the first number in the pair
            num2.index  // index of the second member in the pair
        };

foreach (var pair in pairs)
{
    Console.WriteLine("Pair found: " + pair[0] + ", " + pair[1] +
                      " at line " + pair[2] + ", " + pair[3]);
}

Easily solved by sorting and then using a simple loop: 通过排序然后使用简单的循环轻松解决:

FindPairs(sequence: new[] { 1, 50, 2, 100, 101, 800 }, threshold: 2); // {1, 2}, {100, 101}.

private List<int[]> FindPairs(IEnumerable<int> sequence, int threshold)
{
    var sorted = sequence.OrderBy(x => x).ToList();

    var pairs = new List<int[]>();
    for (var i = 0; i < sorted.Count - 1; ++i)
    {
        if (sorted[i + 1] - sorted[i] <= threshold)
        {
            pairs.Add(new [] { sorted[i], sorted[i + 1] });
        }
    }

    return pairs;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM