Skip to content

Instantly share code, notes, and snippets.

@wataruoguchi
Last active July 31, 2019 03:15
Show Gist options
  • Save wataruoguchi/be74b5fa6cf011e21d09e179750fd62c to your computer and use it in GitHub Desktop.
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.
//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