Last active
July 31, 2019 03:15
-
-
Save wataruoguchi/be74b5fa6cf011e21d09e179750fd62c to your computer and use it in GitHub Desktop.
Given a 2D array containing only 0s and 1s, where each row is sorted. Find the row with the maximum number of 1s.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Given a 2D array containing only 0s and 1s, where each row is sorted. | |
// Find the row with the maximum number of 1s. | |
function getTheRowThatHasMost1s(arr) { | |
const arrWithCount = arr.map((row) => { | |
return {row:row, count: row.filter((num) => num === 1).length}; | |
}); | |
return arrWithCount.reduce((acc, row) => { | |
if (acc.count < row.count) { | |
acc = row; | |
} | |
return acc; | |
}, { count:0 }).row; | |
} | |
const twoDrows = [[0,1,0,0,0,1,0],[0,0,0,1,0,1],[0,0,0,0,1,1,1]]; | |
const res = getTheRowThatHasMost1s(twoDrows); | |
console.log(res, res.join(',') === [0,0,0,0,1,1,1].join(',')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment