Created
March 15, 2017 14:29
-
-
Save ronaiza-cardoso/560fe5e74638292199c7c3cd05716be8 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* 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) |
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;
}
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
Yay https://gist.github.com/lubien/662c9e2e474b123f77420dde3a38a35b
COMPOSE EVERYTHING