使用一个 “O” 字符串的 Y 模式

huangapple go评论63阅读模式
英文:

Pattern of Y using a "O" string

问题

这是我用于“Y”图案的JavaScript代码,但底部不在中心,我的代码有什么问题?将接受奇数。

我期望得到这个输出:

O   O
 O O 
  O  
  O    
  O   

注意:代码部分已被省略,只提供了代码的翻译和预期输出。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const char = &quot;Y&quot;;
const size = 5; //all odd numbers
let output = &quot;&quot;
if (char === &#39;Y&#39;) {
  for (let i = 0; i &lt; size; i++) {
    for (let j = 0; j &lt; size; j++) {
          if (i === j &amp;&amp; i &lt; size / 2 || j === size / 2 &amp;&amp; i &gt;= size / 2 || i + j === size - 1 &amp;&amp; i &lt; size / 2 || (j === 0  &amp;&amp; i &gt;= size / 2))
          {
            output += &#39;O&#39;;
          } else {
            output += &#39; &#39;;
          }
        }
        output += &#39;\n&#39;;
      }
    }
    
console.log(output);

<!-- end snippet -->

I expect to have this output:

O   O
 O O 
  O  
  O    
  O   

答案1

得分: 1

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);
英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const char = &quot;Y&quot;;
const size = 5;
let output = &quot;&quot;
if (char === &#39;Y&#39;) {
  for (let i = 0; i &lt; size; i++) {
    for (let j = 0; j &lt; size; j++) {
          if (i === j &amp;&amp; i &lt; size / 2 || j === size / 2 &amp;&amp; i &gt;= size / 2 || i + j === size - 1 &amp;&amp; i &lt; size / 2 || (j === (size - 1) / 2  &amp;&amp; i &gt;= size / 2)) 
          {
            output += &#39;O&#39;;
          } else {
            output += &#39; &#39;;
          }
        }
        output += &#39;\n&#39;;
      }
    }
    
console.log(output);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 17:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定