-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
51 lines (45 loc) · 1.11 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const { expect } = require('chai');
/**
* @param {number} upper
* @param {number} lower
* @param {number[]} colsum
* @return {number[][]}
*/
let reconstructMatrix = function(upper, lower, colsum) {
const result = [[], []];
if (colsum.reduce((pre, curr) => {
result[0].push(0);
result[1].push(0);
return pre + curr;
}, 0) !== upper + lower) {
return [];
}
for (let i = 0; i < colsum.length; i++) {
if (2 === colsum[i]) {
upper--;
lower--;
result[0][i] = 1;
result[1][i] = 1;
}
}
for (let i = 0; i < colsum.length; i++) {
if (1 === colsum[i]) {
if (upper > 0) {
upper--;
result[0][i] = 1;
} else {
lower--;
result[1][i] = 1;
}
}
}
return (0 === upper && 0 === lower) ? result: [];
};
it('reconstruct-a-2-row-binary-matrix', () => {
expect(reconstructMatrix(2, 1, [1, 1, 1])).to.deep.eq([[1,1,0],[0,0,1]]);
expect(reconstructMatrix(2, 3, [2, 2, 1, 1])).to.deep.eq([]);
expect(reconstructMatrix(5, 5, [2,1,2,0,1,0,1,2,0,1])).to.deep.eq([
[1,1,1,0,1,0,0,1,0,0],
[1,0,1,0,0,0,1,1,0,1]
]);
});