Skip to content

Instantly share code, notes, and snippets.

@dyllandry
Last active June 20, 2021 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyllandry/12bcea043adb2ca1251a8a57ba7e5f20 to your computer and use it in GitHub Desktop.
Save dyllandry/12bcea043adb2ca1251a8a57ba7e5f20 to your computer and use it in GitHub Desktop.
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