Published
Edited
Feb 2, 2018
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
graph = {
const rows = input.trim().split("\n").map(s => s.trim().split(""));
const nodes = {};
const edges = {};
function getId(y, x) {
return `${x},${y},${rows[y][x].toLowerCase()}`;
}
function addEdge(sourceId, y, x) {
// tolerate wonky grids with holes or uneven numbers of rows for now
if (rows[y][x]) {
const targetId = getId(y, x);
edges[sourceId].push(targetId);
}
}
for (let y = 0; y < rows.length; y ++) {
const row = rows[y];
for (let x = 0; x < row.length; x ++) {
const value = row[x].toLowerCase();
const id = getId(y, x);
nodes[id] = value;
if (!edges[id]) {
edges[id] = [];
}
if (x > 0) { // left
addEdge(id, y, x - 1);
if (y > 0) { // up left
addEdge(id, y - 1, x - 1);
}
if (y < rows.length - 1) { // down left
addEdge(id, y + 1, x - 1);
}
}
if (x < row.length - 1) { // right
addEdge(id, y, x + 1);
if (y > 0) { // up right
addEdge(id, y - 1, x + 1);
}
if (y < rows.length - 1) { // down right
addEdge(id, y + 1, x + 1);
}
}
if (y > 0) {
addEdge(id, y - 1, x);
}
if (y < rows.length - 1) {
addEdge(id, y + 1, x)
}
}
}
return { nodes, edges };
}
Insert cell
Insert cell
result = {
const { nodes, edges } = graph;
let words = new Set();
function visit(id, idStack, letterStack) {
if (idStack.includes(id)) {
return;
};
idStack.push(id);
letterStack.push(nodes[id]);
if (letterStack.length >= MIN_LENGTH && t.hasWord(letterStack)) {
words.add(letterStack.join(""));
}
if (t.hasPrefix(letterStack)) {
edges[id].forEach(neighbourId => {
visit(neighbourId, idStack, letterStack);
})
}
idStack.pop();
letterStack.pop();
}
const idStack = [];
const letterStack = [];
Object.keys(nodes).forEach(id => {
visit(id, idStack, letterStack);
})
return [...words].sort((a, b) => b.length - a.length || a.charCodeAt(0) - b.charCodeAt(0));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more