naxor
naxor

Reputation: 7

A function that builds chessboard

I'm trying to answer the following problem from the book 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 chessboard. Passing this string to console.log should show something like this:

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

When you have a program that generates this pattern, define a binding size = 8 and change the program so that it works for any size, outputting a grid of the given width and height." (pg.38, Marijin Haverbeke)

I have come up with the following code. I opted to use an X over spaces to represent the white tiles given it is easier to see. I have come up with the following but the last loop that is supposed to add the new rows and \n isn't working. What is wrong?

function chessBoard (dimension) {
    for (let counter = 0; counter < dimension; counter++) {
        if (boardLine == "") {
            boardLine += "#";
            lastValue = hash;
            console.log(lastValue)
        } else if (lastValue == hash) {
            boardLine += "X";
            lastValue = space;
            console.log(lastValue)
        } else if (lastValue == space) {
            boardLine += "#";
            lastValue = hash;
            console.log(lastValue)
        } else {
          console.log("Error, something went wrong.");
        }
    }
    
    for (let counter2 = 0; counter2 < dimension; counter2++) {
        if (counter2/2 == 0) {
            boardLine += "\n";
            console.log(boardLine)
        } else if (counter2/2 !== 0) {
            boardLine = boardLine + " ";
        } else {
            console.log("Error. Somewhere around here.")
        }
    }
    }
    return boardLine;
}

Upvotes: 0

Views: 91

Answers (1)

Gray Hat
Gray Hat

Reputation: 368

Maybe try something like this...

Short and easy :

Edit : I made the code more human readable. Apologies for the previous answer without proper explanation.

You can check the Spread Syntax for a better understanding.

function chessBoard (dimension) {
    if (!dimension) return "";

    let dimensionlengthArray = new Array(dimension).fill(null);

    // will return a string starting from X
    let line = dimensionlengthArray.map((v,i) => i%2===0?"X":"#").join("");

    // will return a string starting from #
    let reverseLine = [...line].reverse().join("");

    //returns a board starting from line and alternatively filling reverse line
    let board = dimensionlengthArray.map((v,i) => i%2===0?line:reverseLine).join("\n");

    return board;
}

console.log(chessBoard(8));

Upvotes: 1

Related Questions