Learning is a mess
Learning is a mess

Reputation: 8277

Fastest way of finding argmax in 2d array

JavaScript is far from a familiar language to me. I have a piece of logic I am trying to optimise for speed. It consists in finding the argmax, row and columns index, of the a 2d array (rectangular shaped). At the moment, I have a naïve implementation

function argMax2d(arr) {
  var rowMax = 0, colMax = 0;
  for( var rowIndex = 0; rowIndex < arr.length; rowIndex++){
    for( var colIndex = 0; colIndex < arr[rowIndex].length; colIndex++){
      if (arr[rowIndex][colIndex] > arr[rowMax][colMax]){
        rowMax = rowIndex;
        colMax = colIndex;
      }
    }
  }
  return [rowMax, colMax];
}

In Python this would be a really slow way of getting the job done because of making no use of the contiguity of the data.

PS: arr is always rectangular, the number of columns is the same in every row

Upvotes: 2

Views: 187

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Based on the comments in the question, the only minimal optimizations i can think are to cache the length of the arrays to avoid accessing them in each iteration, and the same for the maxValue used for the comparisons.

    function argMax2d(arr) {
      var rowMax = 0,
          colMax = 0,
          vLength = arr.length,
          hLength = arr[0].length,
          maxValue = -Infinity;
          
      for (var rowIndex = 0; rowIndex < vLength; rowIndex++) {
        for (var colIndex = 0; colIndex < hLength; colIndex++) {
          if (arr[rowIndex][colIndex] > maxValue) {
            maxValue = arr[rowIndex][colIndex];
            rowMax = rowIndex;
            colMax = colIndex;
          }
        }
      }
      
      return [rowMax, colMax];
    }

JS performance comparison

Upvotes: 2

Related Questions