It is necessary to lead to this form:

> ***** **** *** ** * ** *** ***** ****** 

where n7 is the number of stars. The 3rd cycle does not work.

 function task7(n7) { for (var i = 0; i < n7; n7--) { for (var j = 1; j < n7; j++) { process.stdout.write("*"); }; console.log('*'); }; var result = ""; for (var k = 1; k < n7; k++) { // не работает, хотя отдельной функцией работает. result = `${result}*`; console.log(result); }; } task7(n7); 

After all, the first two cycles pass and the turn comes to the 3rd, but it does not even start. Where is my logic broken?

  • 2
    You yourself in the first cycle reduce n7-- .. - entithat
  • Thank you, figured out. - dm4
  • @ dm4 added another way to respond to the solution - Lexx918 2:17 pm

2 answers 2

When it comes to the 3rd cycle, n7 is 0. Accordingly, the cycle does not start.

    Your decision is slightly shorter:

    • learn in advance the number of iterations i = (n - 1) * 2 + 1 and in each iteration of the cycle we print the asterisk len -fold using the repeat line method
    • at the end of the iteration, we change the length up or down using the vector len += vector
    • we expand the vector from the direction of decrease towards the increase as soon as we reach the minimum (unit length of the string with asterisks) == 1 && (vector = 1)

     (function(n){ for ( let i = (n - 1) * 2 + 1, len = n, vector = -1; i--; ) { console.log('*'.repeat(len)); (len += vector) == 1 && (vector = 1); } })(4); 

    You can make it even easier if you find the formula for the dependence of the number of stars on the line number. To do this, turn your head 90 degrees to the right looking at your question. You will get something like this:

    enter image description here

    OX and OY axes are striking. Let us draw two straight lines along the tops of the stars: the first of the point {0, 5} in {4, 1} , and the second of {4, 1} in {8, 5} . Now we find the equation of a line passing through two given mismatched points for each of them.

     (y1 - y2) * x + (x2 - x1) * y + (x1 * y2 - x2 * y1) = 0 

    For the first, we get y = 5 - x , for the second, y = x - 3 , where x is the iteration number in your cycle, and y is the number of stars for the repeat function. It remains to add a check in the cycle at the intersection of the middle of the graph. Before him use the first formula, after - the second.

    • Thank you! But this is still far away for me) - dm4