Last active
November 21, 2017 16:01
-
-
Save revazi/57f632c19d44371f81a487189fa45e9b to your computer and use it in GitHub Desktop.
generating pyramid with tail recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var readline = require('readline'); | |
var rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
rl.question("What's the pyramid size? ", function(answer) { | |
var size = parseInt(answer); | |
if (size) { | |
console.log(generatePyramid(size)); | |
} else { | |
console.log("Warning: pyramid size should be an Int."); | |
} | |
rl.close(); | |
}); | |
function generatePyramid(size, numberOfx = 1, numberOfSpaces = size, result = []) { | |
if (size === 0) { | |
return result.join('\n'); | |
} else { | |
result.push(new Array(numberOfSpaces).join(" ") + new Array(numberOfx).fill("X").join("")); | |
return generatePyramid(size - 1, numberOfx + 2, numberOfSpaces - 1, result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment