The figure is ASCII multiline string comprised of minus signs -, plus signs +, vertical bars | and whitespaces. The task is to break the figure in the rectangles it is made of. the function below have written is not working well as per the requirement. and i can not find where the problem. the function is shown below
/**
* Returns the rectangles sequence of specified figure.
* The figure is ASCII multiline string comprised of minus signs -, plus signs +,
* vertical bars | and whitespaces.
* The task is to break the figure in the rectangles it is made of.
*
* NOTE: The order of rectangles does not matter.
*
* @param {string} figure
* @return {Iterable.<string>} decomposition to basic parts
*
* @example
*
* '+------------+\n'+
* '| |\n'+
* '| |\n'+ '+------------+\n'+
* '| |\n'+ '| |\n'+ '+------+\n'+ '+-----+\n'+
* '+------+-----+\n'+ => '| |\n'+ , '| |\n'+ , '| |\n'+
* '| | |\n'+ '| |\n'+ '| |\n'+ '| |\n'+
* '| | |\n' '+------------+\n' '+------+\n' '+-----+\n'
* '+------+-----+\n'
*
*
*
* ' +-----+ \n'+
* ' | | \n'+ '+-------------+\n'+
* '+--+-----+----+\n'+ '+-----+\n'+ '| |\n'+
* '| |\n'+ => '| |\n'+ , '| |\n'+
* '| |\n'+ '+-----+\n' '+-------------+\n'
* '+-------------+\n'
*/
function* getFigureRectangles(figure) {
const lines = figure.split("\n");
const rectangles = [];
for (let y1 = 0; y1 < lines.length; y1++) {
for (let x1 = 0; x1 < lines[y1].length; x1++) {
if (lines[y1][x1] === "+") {
for (let y2 = y1 + 1; y2 < lines.length; y2++) {
for (let x2 = x1 + 1; x2 < lines[y1].length; x2++) {
if (
lines[y2][x2] === "+" &&
lines[y1][x2] === "+" &&
lines[y2][x1] === "+"
) {
const rectangle = [];
for (let y = y1; y <= y2; y++) {
rectangle.push(lines[y].substring(x1, x2 + 1));
}
rectangles.push(rectangle);
// Clear the rectangle from the figure
for (let y = y1; y <= y2; y++) {
lines[y] =
lines[y].substring(0, x1) +
" ".repeat(x2 - x1 + 1) +
lines[y].substring(x2 + 1);
}
}
}
}
}
}
}
for (const rectangle of rectangles) {
yield rectangle.join("\n");
}
}
The algorithm is simple for this, go through the figure, line by line, and find your
(x0,y0)
edges then in the right findx1
edge and down wards to the nearest bottom edge, findy1
. Now you have(x1,y1)
, The assumption is that these are rectangle edges, so verify it by running it through a function that checks if all conditions of a rectangle are satisfied. In this case:'+'
'|'
.Then yield a rectangle drawing when all these checks are satisfied. Yo can follow with the code below.