-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_googleAsGraph.js
141 lines (135 loc) · 2.89 KB
/
js_googleAsGraph.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
const deltas = [[-1, 0], [0, -1], [1,0], [0,1]]
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
]
const countWhiteSpaces = (matrix) => {
let whiteSpaces = 0
for (let row = 0; row < matrix.length; ++row){
for (let column = 0; column < matrix[0].length; ++column){
if (matrix[row][column] === 1){
++whiteSpaces
matrix[row][column] = 0
updateNeighbors(row, column, matrix)
}
}
}
return whiteSpaces
}
const updateNeighbors=(row, column, matrix)=>{
deltas.forEach((rowColumn)=>{
const newColumn = column + rowColumn[0]
const newRow = row + rowColumn[1]
if (validPosition(newRow, newColumn, matrix) && matrix[newRow][newColumn] === 1) {
matrix[newRow][newColumn] = 0
updateNeighbors(newRow, newColumn, matrix)
}
})
}
const validPosition=(row, column, matrix)=>{
if (row < 0 || column < 0 ){ return false }
if (row >= matrix.length || column >= matrix[0].length){ return false }
return true
}
if (process.env['RUN_TESTS']) {
console.log('running tests')
;[
{
name: "empty matrix",
input: [[]],
expected: 0
},
{
name: "single element matrix",
input: [[1]],
expected: 1
},
{
name: "single row, one match",
input: [[0,1]],
expected: 1
},
{
name: "single row, not blob",
input: [[0,1,0,1]],
expected: 2
},
{
name: "single row, two matches",
input: [[0,1,1]],
expected: 1
},
{
name: "two single columns",
input: [[0],
[1]],
expected: 1
},
{
name: "single column blob",
input: [[1],
[1]],
expected: 1
},
{
name: "two column not blob",
input: [[1,0],
[0,1]],
expected: 2
},
{
name: "multi column and row blob, right",
input: [[0,1,0],
[0,1,1],
],
expected: 1
},
{
name: "multi column and row blob, left",
input: [[0,1,0],
[1,1,0],
],
expected: 1
},
{
name: "multi column and row disconnected",
input: [[1,0,0],
[0,1,0],
[0,0,1],
],
expected: 3
},
{
name: "all connected",
input: [[1,1,1],
[1,1,1],
[1,1,1],
],
expected: 1
},
{
name: "Interview case",
input: [
[0,0,0,1,1,0],
[0,0,0,0,0,0],
[0,1,1,0,0,0],
[0,0,1,1,0,0],
],
expected: 2
},
].forEach(function(td){
var actual = countWhiteSpaces(td.input)
var pass = actual === td.expected
if (pass){
console.log("passed:", td.name)
}else{
console.log("failed:", td.name)
console.log("actual:", actual)
console.log("expected:", td.expected)
process.exit()
}
})
}