0

For example, I have an array

arr[5] = {1, 5, 2, 3, 5}

and the highest number is obviously 5.

My question is how do I get both the indices of the highest number (which is 5).

The expected result is 1 and 4.

default locale
  • 13,035
  • 13
  • 56
  • 62
qrnl
  • 49
  • 1
  • 5

3 Answers3

2
var arr = new int[] { 1, 5, 2, 3, 5 };
        int max = arr.Max();
        List<int> indexes = new List<int>();
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] == max)
                indexes.Add(i);
        }
int highindex = indexes.LastOrDefault();
Narek Arzumanyan
  • 616
  • 3
  • 11
1

Thats how you get all indexes of your highest number

var numbers = new int[] { 1, 5, 2, 3, 5 };

int max = numbers.Max();

var indexes = numbers.Select((c, i) => new 
                                       { 
                                          character = c, index = i 
                                       })
                     .Where(list => list.character == max)
                     .ToList();
1

You can use a LINQ query to find the numbers and index that equal the maximum number :

var arr=new[] {1, 5, 2, 3, 5};
var max    = arr.Max();
var indexes= arr.Select( (n,idx)=>n==max?idx:-1)
                .Where(idx=>idx!=-1)
                .ToArray();

This will return {1,4}.

This query uses the Enumerable.Select overload that provides the index of the current element and returns that index if the number is equal to the maximum.

The original title was a bit confusing - how to find the two largest values. You can use a similar query to get the N largest values by selecting the value and index, ordering the results and taking first N items:

var indexes = arr.Select( (val,idx)=> (val:val,idx:idx) )
                 .OrderByDescending(p=>p.val)
                 .Take(2)
                 .Select(p=>p.idx);

This query uses C# 7 tuples to hold the intermediate results and give them a name

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236