I have taken couple days to learn what is Reduce, UseReducer functions (JS, React) so I was thinking maybe I can find something fun to code.
No small chat, here is the question -
2-D Peak Finding - c - - - c - e - z - r s u x - r - a z In the 2d array depicted above, a is a peak, if a >= b, a >= d, a >= e, a >= c, find the peak array. Output should be 'a' var arr = [ [ '', 'c', '', '',''], [ 'c', '', 'e', '','z' ], [ '', 'r', 's', 'u', 'b' ], [ '', 'h', '', 'a','z' ] ];
1. How to compare
'a'>'b' === false
, 'b' > 'a' === true
2. Loop
We split the matrix row by row, and then find the peak for each row.
We know the min is z
console.log(array.reduce(findPeak, 'z')); //split row by row const findPeak = (currPeak, currRow) =>{ //currRow is still an array //So use reduce function again //currRow.reduce(findPeakPerRow, 'z') } const findPeakPerRow = (currPeak, currEle) =>{ //Compare currPeak and CurrEle } //compare function const getMaxValue = (currPeak, currValue) => { //if currValue is not an array, then find the max value return (currValue && currValue < currPeak ? currValue : currPeak) }
Full Codes -
const findPeak = (currPeak, currRow) =>{ let currValue = currRow.reduce(findPeakPerRow, 'z'); return (getMaxValue(currPeak, currValue)); } const findPeakPerRow = (maxValue, currValue) => { return (getMaxValue(maxValue, currValue)); } const getMaxValue = (currPeak, currValue) => { return (currValue && currValue < currPeak ? currValue : currPeak) } console.log(arr.reduce(findPeak, 'z'))
3. Recursive Function?
Not sure if we can convert those to recursive functions...
Feel free to comment any ideas!
Top comments (0)