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

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

Pattern of Y using a "O" string

问题

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

我期望得到这个输出:

  1. O O
  2. O O
  3. O
  4. O
  5. 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 -->

  1. const char = &quot;Y&quot;;
  2. const size = 5; //all odd numbers
  3. let output = &quot;&quot;
  4. if (char === &#39;Y&#39;) {
  5. for (let i = 0; i &lt; size; i++) {
  6. for (let j = 0; j &lt; size; j++) {
  7. 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))
  8. {
  9. output += &#39;O&#39;;
  10. } else {
  11. output += &#39; &#39;;
  12. }
  13. }
  14. output += &#39;\n&#39;;
  15. }
  16. }
  17. console.log(output);

<!-- end snippet -->

I expect to have this output:

  1. O O
  2. O O
  3. O
  4. O
  5. O

答案1

得分: 1

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

  1. const char = "Y";
  2. const size = 5;
  3. let output = "";
  4. if (char === 'Y') {
  5. for (let i = 0; i < size; i++) {
  6. for (let j = 0; j < size; j++) {
  7. 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)) {
  8. output += 'O';
  9. } else {
  10. output += ' ';
  11. }
  12. }
  13. output += '\n';
  14. }
  15. }
  16. 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 -->

  1. const char = &quot;Y&quot;;
  2. const size = 5;
  3. let output = &quot;&quot;
  4. if (char === &#39;Y&#39;) {
  5. for (let i = 0; i &lt; size; i++) {
  6. for (let j = 0; j &lt; size; j++) {
  7. 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))
  8. {
  9. output += &#39;O&#39;;
  10. } else {
  11. output += &#39; &#39;;
  12. }
  13. }
  14. output += &#39;\n&#39;;
  15. }
  16. }
  17. 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:

确定