Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a star triangle using javascript function recursively

I am pretty new to programming, I am getting to know JavaScript, and I've just learned the notion of recursion. Now I am given a problem, to create a function (like const f = function(n) { }) and if we if we call the function with f(5), we should see:

     *
    ***
   *****
  *******
 *********

The number of vertical stars must be determined by the input. I've got to use no for/while/do-while; recursion only to loop.

I've come up with this code to concatenate 5 stars

const f = function(n) {
  if (n === 0) {
    return "";
  }
  return  "*" +  f(n - 1);
};

 console.log(f(5));

Though, I don't see how to make the triangle, what can I do?

like image 516
Erik Hambardzumyan Avatar asked Sep 24 '16 15:09

Erik Hambardzumyan


People also ask

How do you make a star pyramid in Javascript?

function createPyramid(rows) { for (let i = 0; i < rows; i++) { var output = ''; for (let j =0; j < rows - i; j++) output += ' '; for (let k = 0; k <= i; k++) output += '* '; console. log(output); } } createPyramid(5) // pass number as row of pyramid you want.

What are Recursions in Javascript?

Recursion is when a function calls itself until someone stops it. It can be used instead of a loop. If no one stops it, it'll recurse forever and crash your program. A base case is a condition that stops the recursion.


1 Answers

You can use this code:

const f = function(chr, n) {
  if (n === 0) {
    return "";
  }
  return  chr +  f(chr, n - 1);
};
const g = function(max) {
   const inner = function(n) {
       if (n > 1) {
           inner(n-1);
       }
       console.log(f(' ', max-n) + f('*', (n*2)-1));
   };
   inner(max);
};
g(5);
like image 74
jcubic Avatar answered Oct 11 '22 12:10

jcubic