Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
I got this recursion question during an interview and totally blew it. I forgot recursion existed, and my implementation didn't go smoothly. Here's another try.
/**
* I got this recursion question during an interview and totally blew it. I
* forgot recursion existed, and my implementation didn't go smoothly. Here's
* another try.
*
* Question: Print a triangle of stars without using any loops, iteration, etc.
*
* Input: n = 3
* Output: *
* **
* ***
*/
const triangle = getStarTriangle(3);
console.log(triangle);
function getStarTriangle(height, _currentRow = 0, _currentColumn = 0, _currentString = '')
{
// Early exit condition, height may be undefined or 0.
if (!height) return _currentString;
// Recursion end condition.
if (_currentRow == height) return _currentString;
// A) Add star to row
if (_currentColumn <= _currentRow) {
_currentString += '*';
return getStarTriangle(height, _currentRow, ++_currentColumn, _currentString);
}
// B) Create a new row
if (_currentColumn > _currentRow) {
_currentString += '\n';
return getStarTriangle(height, ++_currentRow, 0, _currentString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment