-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11-2d-array.js
More file actions
47 lines (40 loc) · 984 Bytes
/
11-2d-array.js
File metadata and controls
47 lines (40 loc) · 984 Bytes
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
// Write an algorithm which searches through a 2D array,
// Whenever it finds a 0 should set the entire row and column to 0.
// Input:
// [[1,0,1,1,0],
// [0,1,1,1,0],
// [1,1,1,1,1],
// [1,0,1,1,1],
// [1,1,1,1,1]];
// Output:
// [[0,0,0,0,0],
// [0,0,0,0,0],
// [0,0,1,1,0],
// [0,0,0,0,0],
// [0,0,1,1,0]];
// Polynomial Time O(n^k) has a running time that would be some input size n raised to some constant power k.
// This is O(n^2)
const zeroify = (input) => {
let copy = [...input.map((row) => [...row])];
for (let i = 0; i < input.length; i++) {
for (let j = 0; j < input[i].length; j++) {
if (copy[i][j] === 0) transformToZero(input, j, i);
}
}
};
const transformToZero = (input, x, y) => {
input[y].fill(0);
for (let i = 0; i < input.length; i++) {
input[i][x] = 0;
}
return input;
};
const input = [
[1, 0, 1, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
];
zeroify(input);
console.log(input);