Skip to content

Instantly share code, notes, and snippets.

@ronaiza-cardoso
Created March 15, 2017 14:29
Show Gist options
  • Save ronaiza-cardoso/560fe5e74638292199c7c3cd05716be8 to your computer and use it in GitHub Desktop.
Save ronaiza-cardoso/560fe5e74638292199c7c3cd05716be8 to your computer and use it in GitHub Desktop.
/*
* Count Negative Integers in Matrix
*/
M = [
[ -1, 3, 4, 1],
[ 2, 2, 4, 9],
[ 4, 5, -7, 9]
]
function findNegative(M, n, m) {
count = 0
i = 0
j = m - 1
while (j >= 0 && i < n) {
if(M[i][j] < 0){
count += (j + 1)
i += 1
} else {
j -= 1
}
}
console.log(count)
}
findNegative(M, 3, 4)
@lubien
Copy link

lubien commented Mar 15, 2017

Yay https://gist.github.com/lubien/662c9e2e474b123f77420dde3a38a35b
COMPOSE EVERYTHING

@beatorizu
Copy link

Using map and filter

function count_negative(M) {
  var n_count = 0;
  M.map(
    function (row) {
      n_count += row.filter(
        function (item) {
          return item < 0;
        }
      ).length;
    }
  );
  return n_count;
}

@ihavenonickname
Copy link

const countNegatives = mtx => mtx.reduce((acc, x) => acc.concat(x)).filter(x => x < 0).length;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment