Today I went on CodeSignal looking for a fun coding challenge to sharpen my JavaScript skills. I came across an ASCII art problem that looked deceptively simple:
Can you generate a pyramid of asterisks with N rows?
Each level adds two more stars than the level above, centered with proper spacing.
Here's what it looks like for N = 5
:
* *** ***** ******* *********
And for N = 10
? That’s what I set out to build.
⏳ Time Spent: 1 Hour 15 Minutes
I took this challenge seriously—no AI help. I wanted to test my problem-solving process.
Here’s my final code after 75 minutes:
const printChar = "*";
function buildPyramid(rows){
var asteriskCount = rows * 2;
var pyramid = [];
var spaceCount = 0;
for(i = 0; i < rows; i++){
var asterisks = "";
for(c = 0; c < (asteriskCount - 1); c++){
asterisks += printChar;
}
pyramid.push(addSpace(asterisks, spaceCount));
asteriskCount -= 2;
spaceCount += 2;
}
return pyramid.reverse();
}
function addSpace(item, spaceCount){
var before = "", after = "";
const space = " ";
for(i = 0; i < (spaceCount / 2); i++){
before += space;
after += space;
}
return before + item + after;
}
console.log(buildPyramid(10));
🤖 AI's Solution (Much Simpler)
Out of curiosity, I later asked Copilot/AI to solve it, and this was its version:
(Q)Can you write a program that generates this pyramid with a N value of 10 in JavaScript?
function generatePyramid(N) {
for (let i = 1; i <= N; i++) {
const spaces = ' '.repeat(N - i);
const stars = '*'.repeat(2 * i - 1);
console.log(spaces + stars);
}
}
generatePyramid(10);
💡 Takeaways
- Don't overthink simple problems: I went deep with logic and arrays, while the AI focused on core string operations.
- Learning happens in the process: Writing my own solution helped me practice nested loops, string manipulation, and thinking in reverse order.
- AI is a powerful reference, but it's also satisfying to struggle and arrive at your own solution.
If you’re learning JavaScript or just want to keep your brain sharp, try solving small visual problems like this. You’d be surprised how much you can learn from 10 rows of asterisks.
👨🏽💻 Have you solved something cool lately? Drop a link or comment below!
No comments:
Post a Comment