Skip to content

Commit

Permalink
implement island counter
Browse files Browse the repository at this point in the history
  • Loading branch information
grxy committed Dec 3, 2016
1 parent 7e54c73 commit c82cc40
Show file tree
Hide file tree
Showing 3 changed files with 134 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/problems/IslandCounter/IslandCounter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Given a 2D matrix M, filled with either 0s or 1s, count the number of islands of 1s in M.
* An island is a group of adjacent values that are all 1s. Every cell in M can be adjacent
* to the 4 cells that are next to it on the same row or column.
*/

class IslandCounter {
constructor (matrix) {
this.matrix = matrix;
}

count = 0

getCount = () => {
const [ m, n ] = this.getDimensions();

for (let i = 0; i < m; i++) { // iterate over y
for (let j = 0; j < n; j++) { // iterate over x
const current = this.matrix[i][j];

if (current === -1) { // already marked, so mark neighbors
this.markAll(i, j);
} else if (current === 1) {
this.count++;
this.markAll(i, j);
}

}
}

return this.count;
}

getDimensions = () => [this.matrix.length, this.matrix.length ? this.matrix[0].length : 0]

mark = (i, j) => {
const [ m, n ] = this.getDimensions();

if (i >= 0 && i < m && j >= 0 && j < n ) {
if (this.matrix[i][j] === 1) {
this.matrix[i][j] = -1;

this.markAll(i, j);
}
}
}

markAll = (i, j) => {
this.mark(i, j); // mark current
this.mark(i - 1, j); // mark top
this.mark(i, j + 1); // mark right
this.mark(i + 1, j); // mark bottom
this.mark(i, j - 1); // mark left
}
}

export default IslandCounter;
76 changes: 76 additions & 0 deletions src/problems/IslandCounter/IslandCounter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import IslandCounter from './IslandCounter';

describe('IslandCounter', () => {
const cases = [
[
[],
0
],
[
[
[]
],
0
],
[
[
[0]
],
0
],
[
[
[0, 1]
],
1
],
[
[
[1, 1]
],
1
],
[
[
[1],
[0]
],
1
],
[
[
[0],
[1]
],
1
],
[
[
[0, 1, 1],
[1, 0, 0]
],
2
],
[
[
[0, 1, 0, 1, 0],
[0, 0, 1, 1, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 0],
[1, 0, 1, 0, 1]
],
6
]
];

for (let i = 0; i < cases.length; i++) {
const [input, output] = cases[i];
const m = input.length;
const n = input.length ? input[0].length : 0;

it(`works for a ${m}x${n} matrix`, () => {
const counter = new IslandCounter(input);
expect(counter.getCount()).toEqual(output);
});
}
});
1 change: 1 addition & 0 deletions src/problems/IslandCounter/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default from './IslandCounter';

0 comments on commit c82cc40

Please sign in to comment.