Lucky Number:
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
We are required to write a JavaScript function that takes in a two-dimensional array of integers.
The function should find all the lucky numbers in the array, construct a new array and return all the lucky number within that array.
For example −
If the input array is −
const arr = [ [5, 3, 7, 3], [4, 2, 67, 2], [2, 32, 7, 4], [2, 9, 45, 23] ];
Then the output should be −
const output = [];
Example
Following is the code −
const arr = [ [5, 3, 7, 3], [4, 2, 67, 2], [2, 32, 7, 4], [2, 9, 45, 23] ]; const luckyNumbers = (arr = []) => { const column = arr.length; for(let c = 0; c < column; c++){ let minRow = Math.min(...arr[c]); let pos = arr[c].indexOf(minRow); if(minRow === arr[c][pos]){ let tmpMaxColumn = arr[c][pos]; for(let j = 0; j < column; j++){ if(arr[j][pos] > tmpMaxColumn){ tmpMaxColumn = arr[j][pos]; break; } } if(tmpMaxColumn === minRow){ return [tmpMaxColumn]; } } }; return []; }; console.log(luckyNumbers(arr));
Output
Following is the console output −
[]