如何解决 Eloquent Javascript“棋盘”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30225678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:55:21  来源:igfitidea点击:

How do I solve the Eloquent Javascript "Chess Board"?

javascripteloquent

提问by tsaiDavid

new coder here trying to learn JS. I did codecademy already and am working through Eloquent Javascript now. I finally got something together after scratching my head for a very long while... but it doesn't work! I'm not quite sure if I'm approaching this from the right angle but I do know I want to use the loops to track progress through the printing of the # based grid.

新编码员在这里尝试学习 JS。我已经做过 codecademy,现在正在使用 Eloquent Javascript。挠了好久终于搞定了……但是没用!我不太确定我是否从正确的角度接近这个,但我知道我想使用循环来跟踪打印基于 # 的网格的进度。

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board. Passing this string to console.log should show something like this:

编写一个程序,创建一个表示 8×8 网格的字符串,使用换行符分隔行。在网格的每个位置都有一个空格或一个“#”字符。字符应该形成一个棋盘。将此字符串传递给 console.log 应显示如下内容:

 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 

My code is below:

我的代码如下:

    var chessBoard = "";
    var size = 8;

    for (var lineCounter = 1; lineCounter < size; lineCounter++) { 

        if (lineCounter%2 === 0) { /

/if lineCounter is an even number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    (chessBoard += "#");
                    break;
                case false:
                    (chessBoard += " ");
                    break;
                }
            }                   
        }
    else { //if lineCounter is an odd number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    (chessBoard += " ");
                    break;
                case false:
                    (chessBoard += "#");
                    break;
            }
            }                       
        }   
    chessBoard += "\n";
    }
    console.log(chessBoard);

The current output of the program is this:

该程序的当前输出是这样的:

# # # #
 # # # 
# # # #
 # # # 
# # # #
 # # # 
# # # #

Through some iterations, I've already learned a lot, but right now I already see an error - I'm clearly down to a 7x7 grid instead of the 8x8 I wanted to get. I suspect it has to do with me using "<" in my for loops, but not sure if there's a better way to tackle this instead of just adding an extra digit.

通过一些迭代,我已经学到了很多东西,但现在我已经看到了一个错误——我显然是使用 7x7 网格而不是我想要的 8x8 网格。我怀疑这与我在 for 循环中使用“<”有关,但不确定是否有更好的方法来解决这个问题,而不仅仅是添加一个额外的数字。

回答by maioman

It's actually pretty easy you need to make two loops, one for each row and the other for choosing the element you want to console.log (either ' ' or '#').

实际上很容易你需要做两个循环,一个用于每一行,另一个用于选择你想要 console.log 的元素(' ' 或 '#')。

check the comments through solution

通过解决方案检查评论

var size = 8; //this is the variable setting

var board = "";//this is the empty string we're going to add either ' ' , '#' or newline

for (var y = 0; y < size; y++) {   /*in the outer loop we add newline to seperate rows*/
  for (var x = 0; x < size; x++) {/*every inner loop rappresents a line, and alternatively it's adding either ' ' or '#' to the string that's being populated*/
    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}

console.log(board);

回答by Rick Hitchcock

Here's a different approach.

这是一种不同的方法。

Each row has four instances of either _#or #_(where the underscore is a space).

每行都有四个_#or 的实例#_(其中下划线是一个空格)。

Even-numbered rows begin with _#and odd-numbered rows begin with #_:

偶数行以 开头,_#奇数行以 开头#_

var chessBoard= '',
    size= 8,
    c;

for(var i = 0 ; i < size ; i++) {
  c= i%2 ? '# ' : ' #';
  for(var j = 0 ; j < size/2 ; j++) {
    chessBoard+= c;
  }
  chessBoard+= '\n';
}

console.log(chessBoard);

回答by Travis J

jsFiddle Demo

jsFiddle Demo

I am a fan of chess:) In chess, there is the rule "White on right" which means that the first square of our chess board will be " ". Following that it will alternate every time there is an odd match between row and column.

我下棋的粉丝:)在国际象棋中,有规则的“白右边”,这意味着我们的国际象棋棋盘的第一方阵将是“”。此后,每次在行和列之间出现奇数匹配时,它将交替进行。

var board = "";
for(var i = 0; i < 8; i++){
 for(var a = 0; a < 8; a++){
  board += (a % 2) == (i % 2) ? " " : "#";
 }
 board += "\n";
}

Viewing the board, it now shows an 8x8 grid

查看电路板,它现在显示一个 8x8 网格

console.log(board);

 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 

Feel free to substitute ifor a row number or afor a column number. Or set both to a size :) It will still work. For example, a < 20will give 20 columns

随意替换i行号或a列号。或者将两者都设置为一个大小 :) 它仍然可以工作。例如,a < 20将给出 20 列

 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 
 # # # # # # # # # #
# # # # # # # # # # 

回答by Tero Tolonen

Here's a version

这是一个版本

console.log((new Array(65).join().split("")).map( function(v,i) {
    return ( (i/8 >> 0 ) % 2 ? ( i%2 ? " " : "#") : (i%2 ? "#" : " ") ) +
           ( (i+1) %8 ? "" : "\n" );
}).join(""));

回答by Karl Mendes

var chessBoard = "";
var size = 8;

for (var lineCounter = 1; lineCounter < size; lineCounter++) { 

    if (lineCounter%2 === 0) { //if lineCounter is an even number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    chessBoard += "#";
                    break;
                case false:
                    chessBoard += " ";
                    break;
                }
            }                   
        }
    else { //if lineCounter is an odd number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    chessBoard += " ";
                    break;
                case false:
                    chessBoard += "#";
                    break;
            }
        }                       
    }   
    chessBoard += "\n";
}
console.log(chessBoard);

回答by Noah Johnson

Using only the knowledge provided up to that point in the book Eloquent JavaScripthere is my solution:

仅使用Eloquent JavaScript一书中提供的知识,这是我的解决方案:

   var board = "";
   var size = 8;

   // Outer for loop creates a new line** after each cycle of the inner for loop
   for (var lineCount = 0; lineCount < size; lineCount++) {
       //The nested for loop adds a character to the board variable on a single line proportional to the size variable
       for (var spaceCount = 0; spaceCount < size; spaceCount++) {
           //This if statement creates the offset lines in the example image by alternating the first character depending on the lineCount
           if (lineCount % 2 == 0) {
               var black = "#",
                   white = " ";
           } else {
               black = " ";
               white = "#";
           }
           if (spaceCount % 2 == 0) {
               board += white;
           } else {
               board += black;
           }
       }
       board += "\n"; //** new line created
   }
   console.log(board);

回答by vickig

I did the following... It's not very eloquent but it worked for the scenerio.

我做了以下...这不是很有说服力,但它适用于场景。

var hash = ' # #';
var rehash = '# # ';
for( var i = 1; i<9; i++){
  if( i%2 ==0){
    console.log(rehash+ rehash);}
  else{
    console.log(hash + hash);}
}

回答by Thyag

I used two independent FOR loops and it worked. Hopefully independent FOR loops makes it readable. Size of the board can be modified and it reflects accordingly.

我使用了两个独立的 FOR 循环并且它起作用了。希望独立的 FOR 循环使其可读。板的大小可以修改,并相应地反映。

size = 8
oddline  = ""
evenline = ""

/*First for loop is for creating the first and second lines*/
for (i=0;i<size/2;i++)
{
    oddline = oddline + "#" + " "
    evenline = evenline + " " + "#"
}

/* This for loop is for printing the first and second lines repeatedly */
for (j=0;j<size/2;j++)
{
console.log(oddline)
console.log(evenline)
}

回答by Thyag

Not the most elegant solution I'm sure but it works.

我确定这不是最优雅的解决方案,但它有效。

let chessBoard = "";
const boardSize = 8;

for (let yAxis = 0; yAxis < boardSize; yAxis++) {
  for (let xAxis = 0; xAxis < (boardSize / 2); xAxis++) {
    if (yAxis % 2 === 0) {
      chessBoard += " ";
      chessBoard += "#";
    }
    else {
      chessBoard += "#";
      chessBoard += " ";
    }
  }
  chessBoard += "\n";
}
console.log(chessBoard)

回答by Jon Love

I created a solution using the String.repeatmethod that I think is much cleaner than many of the solutions here:

我使用String.repeat方法创建了一个解决方案,我认为它比这里的许多解决方案更清晰:

var size = 8;
var grid = "";

for (i = 1; i <= size; i++) {
  if (i%2 == 0)
    grid += "# ".repeat(size/2) + "\n";
  else
    grid += " #".repeat(size/2) + "\n";
}

console.log(grid);