Home > Net >  finding nth biggest element in multidimensional array
finding nth biggest element in multidimensional array

Time:11-05

how can I find 5th or 7th, or 15th biggest element in multidimensional array without existing methods (like list.Add) I will be pleased if you write it in c#

int[,,,] x =new int[100, 20, 35, 200];

...

int indis  = 0;
int toplam = 0;
int enss   = 0;

for (int i = 0; i < 100; i  ) {
  for (int j = 0; j < 20; j  ) {
    toplam = 0;

    for (int k = 0; k < 35; k  ) {
      for (int l = 0; l < 200; l  ) {
        toplam  = x[i, j, k, l];
      }
    }

    if (toplam > enss) {
      enss  = toplam; 
      indis = j;
    }
  }
}

CodePudding user response:

You can try to query with a help of Linq (let .NET use Add if it wants). The crucial thing is to treat multidimensional array T[,,,] as IEnumerable<T>; we can use OfType() for this. Having IEnumerable<T> we can solve the rest. To find max item, just call Max():

using System.Linq;

...

int[,,,] x = new int[100, 20, 35, 200];

...

int max = x.OfType<int>().Max();

If you want to find nth biggest item, you can sort, skip n - 1 items and take the first:

...

int n = 7;

int maxN = x
  .OfType<int>()
  .OrderByDescending(item => item)
  .Skip(n - 1)
  .First();

CodePudding user response:

Using linq :

           var table = Enumerable.Range(0, x.GetLength(0))
                .SelectMany((a, i) => Enumerable.Range(0, x.GetLength(1))
                .SelectMany((b, j) => Enumerable.Range(0, x.GetLength(2))
                .SelectMany((c, k) => Enumerable.Range(0, x.GetLength(3)
                .Select((d, l) => new { x = x[i, j, k, l], i = i, j = j, k = k, l = l }))))
                .OrderByDescending(x => x.x);
  • Related