Please I am trying to print out a hollowed rectangle according to what length and width that the user gives to the command but I can't seem to wrap my head around how I can achieve that. I have tried so many iterations of my code below without archiving the required result. Below is the code:
function printRectangle(rows, cols) {
let i, j;
for (i = 0; i <= rows; i++) {
for (j = 0; j <= cols; j++) {
if (i < 2 || i === rows || j < 2 || j <= cols - 15) {
process.stdout.write('*');
} else {
if (i < 2 || i === rows || j === 2 || j <= cols - 5) {
process.stdout.write(' ');
}
// process.stdout.write(' ');
}
}
process.stdout.write('*****\n');
}
}
// user imputs
let rows = 10,
columns = 30;
printRectangle(rows, columns);
I am printing it on the command line using node.js. below is my desired result and what I have been getting: The desired result that I should print out
function printRectangle(rows, cols) {
let i, j;
for (i = 0; i <= rows; i++) {
for (j = 0; j <= cols; j++) {
if (i < 2 || i === rows || j < 2 || j <= cols - 15) {
process.stdout.write('*');
} else {
if (i < 2 || i === rows || j === 2 || j <= cols - 5) {
process.stdout.write(' ');
}
// process.stdout.write(' ');
}
}
process.stdout.write('*****\n');
}
}
// user imputs
let rows = 10,
columns = 30;
printRectangle(rows, columns);
This would work. I used console.log so that you can view the demo
const spaceWidth = 21;
const spaceHeight = 3;
function printRectangle(rows, cols) {
let result = '';
const borderWidth = (cols - spaceWidth) / 2;
const borderHeight = (rows - spaceHeight) / 2;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const rowIsBorder = i < borderHeight || i >= borderHeight + spaceHeight;
const colIsBorder = j < borderWidth || j >= borderWidth + spaceWidth;
result += rowIsBorder || colIsBorder ? '*' : ' ';
}
result += '\n';
}
console.log(result);
}
printRectangle(9, 31);