-
Notifications
You must be signed in to change notification settings - Fork 187
/
graphFromAscii.js
109 lines (86 loc) · 1.98 KB
/
graphFromAscii.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
var createGraph = require('ngraph.graph');
var EMPTY_CELL = '.'
var WALL = '@'
module.exports = {
graphFromTextArray,
graphToTextGrid,
nodeId
};
function graphFromTextArray(lines) {
var graph = createGraph({uniqueLinkIds: false});
var cols = 0;
var rows = lines.length;
lines.forEach((line, row, lines) => {
if (line.length > cols) cols = line.length;
Array.from(line).forEach((symbol, col) => {
if (symbol !== EMPTY_CELL) return;
var id = nodeId(row, col);
graph.addNode(id, { x: col, y: row })
if (col > 0 && line[col - 1] !== WALL) {
graph.addLink(id, nodeId(row, col - 1));
}
if (row === 0) return;
var prevLine = lines[row - 1];
if (prevLine.length <= col) return;
if (prevLine[col] === EMPTY_CELL) {
graph.addLink(id, nodeId(row - 1, col));
}
})
})
graph.cols = cols;
graph.rows = rows;
return graph;
}
function nodeId(row, col) {
return row + ';' + col;
}
class TextGrid {
constructor(rows, cols, fillSymbol = EMPTY_CELL) {
this.rows = rows;
this.cols = cols;
this.fill(fillSymbol);
}
toString() {
return this.grid.map(l => l.join('')).join('\n');
}
drawPath(path) {
var grid = this;
path.forEach(p => {
grid.draw(p.x, p.y, '#');
})
}
draw(x, y, symbol) {
this.grid[y][x] = symbol;
}
fill(symbol) {
var grid = [];
for (var i = 0; i < this.rows; ++i) {
var line = [];
grid.push(line);
for (var j = 0; j < this.cols; ++j) {
line[j] = symbol;
}
}
this.grid = grid;
}
}
function graphToTextGrid(g) {
var grid = new TextGrid(g.rows, g.cols, WALL);
g.forEachNode(node => {
grid.draw(node.data.x, node.data.y, EMPTY_CELL)
})
return grid;
}
// var graph = graphFromASII([
// '....',
// '..@.',
// '....',
// '....'].join('\n')
// )
// var grid = graphToASCII(graph);
// grid.drawPath([{
// x: 0, y: 0
// }, {
// x: 1, y: 1
// }])
// console.log(grid.toString());