0

I am a new web developer and need assistance generating a given output to a problem:

var totalNumberofRows = 5; 
var output = '';
for (var i = 1; i <= totalNumberofRows; i++) {
    for (var j = 1; j <= i; j++) {
        output +=  i;
     }
    console.log(output+' ');
    output = '';
}

Output:

1
22
333
4444
55555 

Expected Output:

1
22
333
55555
88888888

How would I be able to make my code produce the target output?

JeanJacquesGourdin
  • 1,496
  • 5
  • 25
Suresh T
  • 3
  • 2
  • 4
    Why do you expect a non-sequential output when the loop is sequential? – Yogi Sep 25 '22 at 07:13
  • 3
    Can you explain more about the expected output ? Right now, just doing ```console.log(1); console.log(22);...``` is a solution, but i guess it's not what you want – JeanJacquesGourdin Sep 25 '22 at 07:13
  • 2
    Are you supposed to output a fibonacci sequence? – Sheraff Sep 25 '22 at 07:23
  • Does this answer your question? [Generating Fibonacci Sequence](https://stackoverflow.com/questions/7944239/generating-fibonacci-sequence) – Yogi Sep 25 '22 at 07:45

4 Answers4

3

For non-sequential numbers you could use an array with the String.repeat method:

[1, 2, 3, 5, 8].forEach(n => console.log(n.toString().repeat(n)));
Yogi
  • 6,241
  • 3
  • 24
  • 30
1

If you want to output the fibonachi sequence you can do :

let current = 1
let last = 0

for (let i = 0; i < 5; i++) {
  console.log(Array(current+last).fill(current+last).join(''))
  let toLast = current
  current += last
  last = toLast
}
JeanJacquesGourdin
  • 1,496
  • 5
  • 25
0

Have you intended something similar to the Fibonacci sequence?

var totalNumberofRows = 5;
var output = '';

for (var i = 1; i <= totalNumberofRows; i++) {
    var next = fibo(i + 1);
    
    for (var j = 1; j <= next; j++) {
        output += next;
    }

    console.log(output + ' ');
    output = '';
}

function fibo(n) {
  let result = [0, 1];

  for (let i = 2; i <= n; i++) {
    const a = result[i - 1];
    const b = result[i - 2];

    result.push(a + b);
  }

  return result[n];
}
  • I feel really bad because of this answer, you are computing again and again the same values, this is a typical use case of dynamic programming. Please edit with an optimised version, you just need to add an array holding the preceding values of the sequence, so that you dont have to compute it again. This edit will make the time complexity ~O(N) instead of something like ~O(n^2) – JeanJacquesGourdin Sep 25 '22 at 11:31
  • Thanks ! That's almost it ! The thing with your current solution is that you still compute again every value of the sequence for every new number asked to fibo(), you need put the array outside of the fibo() function so that it is remembered. – JeanJacquesGourdin Sep 26 '22 at 05:36
0

[1, 2, 3, 5, 8].map(item => console.log(item.toString().repeat(item)));
Asif vora
  • 3,163
  • 3
  • 15
  • 31