Skip to content

Commit ad648f6

Browse files
committed
Improve local to go in one pass
1 parent 84251aa commit ad648f6

File tree

1 file changed

+35
-9
lines changed

1 file changed

+35
-9
lines changed

simple_loop_interface/script.js

+35-9
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,40 @@ class Grid {
252252
return true;
253253
}
254254

255+
localInclude(r, c, handled) {
256+
if (this.cells[r][c] || handled.has(JSON.stringify([r, c]))) {
257+
return false;
258+
}
259+
let possible = this.neighbors([r, c]).filter(([node, edge]) => this.edges[edge] !== "unused");
260+
let used = possible.filter(([node, edge]) => this.edges[edge] === "used");
261+
return (used.length < possible.length) && (possible.length <= 2 || used.length >= 2);
262+
}
263+
264+
local() {
265+
const rows = this.cells.length;
266+
const cols = this.cells[0].length;
267+
const stack = [];
268+
const handled = new Set();
269+
for (let r = 0; r < rows; r++) {
270+
for (let c = 0; c < cols; c++) {
271+
if (this.localInclude(r, c, handled)) {
272+
stack.push([r, c]);
273+
handled.add(JSON.stringify([r, c]));
274+
}
275+
}
276+
}
277+
while (stack.length > 0) {
278+
let [r, c] = stack.pop();
279+
this.adjustEdges(new Set([JSON.stringify([r, c])]));
280+
for (let [[nr, nc], _] of this.neighbors([r, c])) {
281+
if (this.localInclude(nr, nc, handled)) {
282+
stack.push([nr, nc]);
283+
handled.add(JSON.stringify([nr, nc]));
284+
}
285+
}
286+
}
287+
}
288+
255289
parity1() {
256290
let m = this.cells.length;
257291
let n = this.cells[0].length;
@@ -401,15 +435,7 @@ window.onload = function () {
401435
}, 'p');
402436

403437
createButton('Parity on each cell (l)', function () {
404-
const rows = grid.cells.length;
405-
const cols = grid.cells[0].length;
406-
for (let r = 0; r < rows; r++) {
407-
for (let c = 0; c < cols; c++) {
408-
if (!grid.cells[r][c]) {
409-
grid.adjustEdges(new Set([JSON.stringify([r, c])]));
410-
}
411-
}
412-
}
438+
grid.local();
413439
}, 'l');
414440

415441
createButton('Parity 1 (1)', function () {

0 commit comments

Comments
 (0)