Home > front end >  Find max value in each of the index of a collection of integers in c# [closed]
Find max value in each of the index of a collection of integers in c# [closed]

Time:10-06

I have a List<List<int>>. All the list will be of equal size. I need to find the max value in every index of the list.

ie if I have 100 list each of size 3. I need to find the max value at index 0,1 and 2 across the 100 items.

ie

Max value out of list1[0], list2[0], list3[0],......list100[0]
Max value out of list1[1], list2[1], list3[1],......list100[1]
Max value out of list1[2], list2[2], list3[2],......list100[2]

Need a function which accepts the List<List<int>> and returns an list with max value of each index. Like below

public List<int> FindMaxValueByIndex(List<List<int>> items)
{
}

Performance is a key factor that needs to be considered.

CodePudding user response:

Ignoring data validation & guaranteeing the inner lists will always have the same number of elements:

public List<int> FindMaxValueByIndex(List<List<int>> items)
{
    var maxListSize = items[0].Count;

    var maxValues = new List<int>(items.Count);

    for (var index = 0; index < maxListSize; index  )
        maxValues.Add(items.Select(x => x[index]).Max());

    return maxValues;
}

Input:

var data = new List<List<int>>
{
    new List<int> { 5, 10, 300, 1 },
    new List<int> { 3, 24, 2, 56 },
};

Output:

{5, 24, 300, 56}

CodePudding user response:

I would recommend such approach using LINQ methods :)

private static int[] FindMaxByIndex(List<List<int>> lists)
{
    var listLength = lists
        .Select(x => x.Count)
        .Distinct()
        // If all lists are of equal length
        // this should contain single element.
        // Otherwise this would throw exception - 
        // this is validation.
        .Single();

    var maxesByIndex = new int[listLength];

    for (int i = 0; i < listLength; i  )
    {
        maxesByIndex[i] = lists
            .Select(x => x[i])
            .Max();
    }

    return maxesByIndex;
}

CodePudding user response:

I understand that the question states that the lists will always be the same size, however, since a generic list of generic lists is used and a generic list of generic lists does not enforce that requirement, this code takes the safe approach of ensuring that out of bounds indices are not accessed.

public List<int> FindMaxValueByIndex(List<List<int>> items)
        {
            List<int> ret = new List<int>();
            var MaxListSize = items.Select(l => l.Count).Max();
            for(int i = 0; i < MaxListSize; i   )
            {
                ret.Add(items.Where(l => l.Count > i).Select(l => l[i]).Max());
            }
            
            return ret;
        }

Fiddle

  • Related