Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

49
Views
JavaScript pattern to display in browser

I am trying to make a Javascript pattern that accepts a user input in the form of a digit and returns the below output:

******1 
****1 2 1
***1 2 2 1
**1 2 3 2 1
*1 2 3 3 2 1
1 2 3 4 3 2 1
*1 2 3 3 2 1
**1 2 3 2 1
***1 2 2 1
****1 2 1
*****1

However I am stuck at the a pattern that looks like this:

         1
       1 2 1
     1 2 3 2 1
   1 2 3 4 3 2 1
     1 2 3 2 1
       1 2 1
         1

This is the code I wrote until now.

function selectNo() {
  var selectedNo = document.getElementById("select-number").value;
  for (var i = 1; i <= selectedNo; i++) {
    for (var l = 0; l < (selectedNo - i); l++)
      document.write("&nbsp;&nbsp; ")
    for (var j = 1; j <= i; j++)
      document.write(" " + j)
    for (var k = i - 1; k >= 1; k--)
      document.write(" " + k)
    document.write("<br>");
  }
  for (var i = 1; i <= selectedNo; i++) {
    for (var l = 0; l < i; l++)
      document.write("&nbsp;&nbsp; ")
    for (var j = 1; j <= (selectedNo - i); j++)
      document.write(" " + j)
    for (var k = selectedNo - i - 1; k >= 1; k--)
      document.write(" " + k)
    document.write("<br>");
  }
}
<input type="number" id="select-number" placeholder="Select your number">
<button onclick="selectNo()">Print the pattern</button>

Any suggestions on how to reach the target pattern? Thank you!

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Create a function that returns the array of the next numbers and then you can loop from 1 to the input number. Then you just need to join the arrays.

function line(len) {
    const middle = (len - 1) / 2;
    const a = [];
    for(let i = 0; i < len; i++) {
        if(i < middle) {
            a.push(i + 1);
        }
        else {
            a.push(len - i);
        }
    }
    return a;
}

function diamond(len) {
    l = len * 2 - 1;
    const d = [];
    for(let i = 0; i < l; i++) {
        const a = line(i + 1).map(v => `${v} `);
        const b = new Array(l - a.length).fill('&nbsp;').concat(a).join('');
        d.push(b);
    }
    for(let i = l - 2; i >= 0; i--) {
        const a = line(i + 1).map(v => `${v} `);
        const b = new Array(l - a.length).fill('&nbsp;').concat(a).join('');
        d.push(b);
    }
    return d.join('<br/>');
}

function main() {
  document.getElementById("result").innerHTML = diamond(document.getElementById("val").value);
}
<input id="val" type="number" placeholder="Select your number">
<button onclick="main()">Print the Pattern</button>
<div id="result" style="font-family: monospace;"></div>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs