Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pattern of Y using a "O" string

This is my javascript code for the Y pattern but in the bottom part, it is not in the center what’s wrong with my code? will accept odd numbers

const char = "Y";
const size = 5; //all odd numbers
let output = ""
if (char === 'Y') {
  for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
          if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === 0  && i >= size / 2))
          {
            output += 'O';
          } else {
            output += ' ';
          }
        }
        output += '\n';
      }
    }
    
console.log(output);

I expect to have this output:

O   O
 O O 
  O  
  O    
  O   

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Changing j === 0 to j === 2 will solve this problem. For work universally, just use j === (size - 1) / 2

const char = "Y";
const size = 5;
let output = ""
if (char === 'Y') {
  for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
          if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === (size - 1) / 2  && i >= size / 2)) 
          {
            output += 'O';
          } else {
            output += ' ';
          }
        }
        output += '\n';
      }
    }
    
console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading