Miguel Oz
asked on
Find the top N values of a 2D array
Dear experts:
Basically I would like to implement the following method:
[ 0 3 2 1
4 2 1 5
1 6 2 1 ]
If I want to find the top 3 values, the method call will be:
FindTopValues(data, 3)
and the results will be: (row,col, value)
2,1,6
1,3,5
1,0,4
Further array details:
- Number of rows >= 5* Number of rows
- Values in array between 0 and 10000.
Thanks,
MAS
Code is in C# , but VB.NET/C++ answers are OK.
Basically I would like to implement the following method:
public List<SearchResults> FindTopValues(int[,] data, int howManyTops)
{
List<SearchResults> results = new List<SearchResults>();
//Your code goes here.
return results;
}
wherepublic class SearchResults
{
public int Row { get; set; }
public int Col { get; set; }
public int Value { get; set; }
}
For example given the data array[ 0 3 2 1
4 2 1 5
1 6 2 1 ]
If I want to find the top 3 values, the method call will be:
FindTopValues(data, 3)
and the results will be: (row,col, value)
2,1,6
1,3,5
1,0,4
Further array details:
- Number of rows >= 5* Number of rows
- Values in array between 0 and 10000.
Thanks,
MAS
Code is in C# , but VB.NET/C++ answers are OK.
Hi mas_oz2003;
Here is another solution.
Here is another solution.
public List<SearchResults> FindTopValues(int[,] data, int howManyTops)
{
List<SearchResults> results = new List<SearchResults>();
for(int i = 0; i < data.GetUpperBound(1); i++ ){
for(int j = 0; j <= data.GetUpperBound(1); j++ ){
results.Add(new SearchResults() { Col = j, Row = i, Value = data[i,j]});
}
}
return results.OrderByDescending(r => r.Value).Take(howManyTops).ToList();
}
@FenandoSoto
Shouldn't your first GetUpperBound call be looking at the first dimension (i.e. zero)?
Shouldn't your first GetUpperBound call be looking at the first dimension (i.e. zero)?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Both solutions work OK, but Kaufmed code has a better performance for big arrays
Open in new window