I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("  ");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write(" ");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
I'm trying to 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:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
When you have a program that generates this pattern, define a variable size = 8 and change the program, so that it works for any size, outputting a grid of the given width and height.
var hash = "#";
var space = ' ';
var size = 8;
for (var x = 1; x <= size; x++); {
var line = ' ';
for (var y = 1; y <= size; y++); {
if (x % 2) {
if (y % 2) {
line = line + space;
} else {
line = line + hash;
}
} else {
if (y % 2) {
line = line + hash;
} else {
line = line + space;
}
}
}
console.log(line);
}
I'm having trouble figuring out why this is not working...:(
Remove the semicolons at the end of your loops:
for (var x = 1; x <= size; x++) {
var line = ' ';
for (var y = 1; y <= size; y++) {
With the semicolons, the engine will do the following:
Run the stuff after 'for' inside the brackets - i will be 10 afterwards
stuff inside the curly brackets will be executed once afterwards
If you add a line break it becomes obvious
for (var i = 0; i < 10; i++);
{console.log(i);}
The curly braces are not the body of the for, but a new block.
Make sure you remove ; - s in front of for loops, because of that your for loops are not properly executing logic inside brackets (code will just run once):
Something like this will do what you want:
var size = 8;
for (var y = 0; y < size; y++) {
var line = ' ';
for (var x = 0; x < size; x++) {
line += (y + x + 1) % 2 ? ' ': '#';
}
console.log(line);
}
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.
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:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
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.
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 '#').
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);
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
console.log(board);
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Feel free to substitute i for a row number or a for a column number. Or set both to a size :) It will still work. For example, a < 20 will give 20 columns
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
Here's a different approach.
Each row has four instances of either _# or #_ (where the underscore is a space).
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);
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(""));
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);
Using only the knowledge provided up to that point in the book Eloquent JavaScript here is my solution:
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);
here is my version.
Is not as clean and eloquent as the book one but it works!
var size = 8;
var board = " ";
for (var z = 0; z < size; z++) {
for (var y = 1; y < size; y++) {
if (board[y-1]===" ")
board += "#";
else
board += " ";
}
board += "\n";
console.log(board);
if (board[0]===" ")
board = "#";
else
board = " ";
}
var size = 8;
var block = '#';
var space = ' ';
for (var i = 1; i <= size; i++) {
var line = '';
for (var y = 1; y <= size; y++){
if (i%2) {
if (y%2) {
line = line + space;
} else {
line = line + block;
}
} else {
if (y%2) {
line = line + block;
} else {
line = line + space;
}
}
}
console.log(line);
}
That's my solution:
var size=8, line="", c="";
for (i=0;i<size;i+=1){
i%2==0?c=" ":c="#";
for(n=0;n<size;n+=1){
c==" "?c="#":c=" ";
line+=c;
}
console.log(line);
line=""
}
just wanted to add mine :)
var times = 8; //set the times you want to run the loop
var result = '';//result is the chessboard.
for(var i = 0; i < times; i++){ //run the loop starting at zero and going up.
for(var x = 0; x <= 4; x++){ //run a second loop to run each line of the chessboard.
if(i % 2 === 0){ //check if i(current index of the loop) is divisible by 0, and concatenate '# ' to result
result += '# ';
}else{ //if not divisible by 0 then concatenate ' #'
result += ' #';
}
}
result = result + '\n' //add a line brake to at the end of every index
}
console.log(result); //result should now print the chessboard.
So me and some coding buddies were going back and forth optimizing this function for fun and education.
I didn't see our winning solution up here so why not throw it up?
function board(size) {
// determine if we're dealing with an odd board size
var odd=size%2,
// get size-1 if odd, so we can simplify things
s=odd?size-1:size,
// our first row base
r1 = " #",
// our first row
row1 = r1,
// our second row base
r2 = "# ",
// our second row
row2 = r2,
// total size of board, including newlines
total = (size*size)+size,
// our output
out = "",
// our board base
o;
// if size was 1, then it would be odd and s = 0
// in that case return first row, first character
// just a single white space
if(!s) {
return r1[0];
}
// next we build our rows with 2 loops
// this first loop doubles each row until we're within 2*n of total length
// we'd want to skip this step for small values of size
for(n=2;2*n<s;n*=2) {
row1+=row1;
row2+=row2;
}
// this second loop adds our bases until we have the size length
while(row1.length<s) {
row1+=r1;
row2+=r2;
}
// if our size is odd, then a row ends with the same character it begins with
if(odd) {
row1+=r1[0];
row2+=r2[0];
}
// add our newlines to complete our rows
row1+="\n";
row2+="\n";
// we do the same thing to build the board, 2 loops
// start with our base of the 2 rows we just built
out = o = row1+row2;
// double up the rows until we're within 2*n rows of a full board
// again, we'd want to skip this step for small values of size
for(n=2;2*n<s;n*=2) {
out+=out;
}
// add the base until we're complete or 1 row off (if odd)
while(out.length+size+1<total) {
out+=o;
}
// if odd add the first row as final row
if(odd) {
out+=row1;
}
// return the completed chessboard string
return out;
}
// function call with size, returns our chessboard string
console.log(board(8));
If you remove the for(n=2;2*n<s;n*=2) loops then it'll run faster for generating smaller boards but keeping them in makes it much more efficient for larger boards. Ideally you could calculate and specify a threshold and skip the for loops when size<threshold.
this might be late but there are answers on the from the page itself see: http://eloquentjavascript.net/code/
manipulate for loop/formulas for understanding like
var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
for (var x = 0; x < 1; x++) {
if ((x + y) % 2 == 0)
board += (x+y)+"%";
else
board += (x+y)+"#";
}
board += "\n";
}
console.log(board);
I tried mine with while loops and a basic understanding of the books solution.
var board = ""
var size = 8
var x = 0
var y = 0
while (x < size) //restricts number of rows "size" times
{
while (y < size) //changes value of board to board+= # or " " a combined "size" times restricting columns to "size"
{
if ((x+y) % 2 == 0) //adding x+y ensures each row begins with altering #/_
board += " "; //increases value of board by _
else
board += "#"; //increases value of board by _
y++; // increases from 0-8 allowing loop to execute 8 times.
}
board += "\n";
x++; // increases from 0-8 allowing loop to execute 8 times.
y = 0; //resets vaule of y to 0 to allow inner loop to repeate
}
console.log(board) // board prints as a repeating string of #_ using line breaks to create new rows
var sizeX = 8,
sizeY = 8;
var emty = " #",
grid = "# ";
for (x = 0; x < sizeX; x++) {
if (x % 2) {
console.log(emty.repeat(sizeY))
} else {
console.log(grid.repeat(sizeY))
}
}
Here it goes an alternative answer using ternary operator (my first contribution :D):
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 i = 0; i < size; i++) { /*in the outer loop we add newline to separate rows*/
for (var j = 0; j < size; j++) {/*every inner loop represents a column, and alternatively it's adding either ' ' or '#' to the string that's being populated*/
((i+j%2==0 ? board+=" ": board+="#") /*Here you can see the ternary operator. The syntax = condition ? true: false */
}
board+="\n";
};
console.log(board);
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);}
}
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.
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)
}
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)
I created a solution using the String.repeat method that I think is much cleaner than many of the solutions here:
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);
function PrintChessBoard(x,y){
var newHashString = CreateHashString(8);
var charArray = newHashString.split('');
//var tempArry =[];
for(var i = 1 ; i<=y ;i++)
{
if(i % 2 ==0){
for(var j=0 ; j<x; j=j+2){
charArray[j+1] = ' ';
}
}
else{
for(var k=0 ; k<x ; k += 2){
charArray[k] = ' ';
}
}
var HashString = ConcatArrayToString(charArray)
//reset array
charArray = newHashString.split('');
console.log(HashString);
}
}
function CreateHashString(x){
var hashString = '';
while(x>0){
hashString +='X';
x--;
}
return hashString;
}
function ConcatArrayToString(arr){
var nS ='';
for(var i = 0 ; i<arr.length ;i++){
nS +=arr[i];
}
return nS;
}
PrintChessBoard(8,8);
In case someone wonders, there is a way to do this with only one loop:
var chess="";
var size=8;
var k=0, l=1;
//k is to check even for now
//l is for odd for now
var tmp;
var isEven=false;
//we check if chess is Even (if not isEven stays false)
if(size%2==0)
isEven=true;
//sqSize tells us how many chess squares are there
sqSize= size*size;
for(var i=1; i<sqSize+1;i++){
/*
At the beginning of loop we check if the i is even
When we have even ches e.g. 8x8 we need to swap condition
every line (is i even? ----> is i odd? ---->etc.)
*/
if (i%2==k)
chess+=" ";
else
chess+="#";
if (i%size==0){
chess+="\n";
//Adding new line every "size" number.
/*
Here the the swap happens
Earlier, we checked if the size is odd or even.
Now we use this knowledge.
k is condition value. we swap 0 to 1, so we will
be checking different condition in the next loop passing.
*/
if(isEven==true){
tmp=k;
k=l;
l=tmp;
}
}
}
console.log(chess);
The official solution uses the newline character /n which I understand. By nesting the two for loops inside of each other, you can build up the whole chess board in one line. Sure.
But if I want to build an oddRow (starting with # and repeating across the width) and an evenRow (starting with _ and repeating across the width) separately, then print each row sequentially with a new console.log function here's how I did it.
The reason I'm taking this approach was because printing multiple console.log lines was just used in exercise 2.1 "looping a triangle" of the same book. It appears more logical to me, and this works.
var size = 8;
var evenRow = "";
var oddRow = "";
for (var j = 0; j < size; j++) {
evenRow += " #";
oddRow += "# ";
}
for (var i = 0; i < size; i++) {
if (i % 2 == 0) //even
console.log(evenRow);
else //odd
console.log(oddRow);
}
Here is another simplified version of this:
function chessBoard(symbol, gridSize) {
gridSize = gridSize || 8;
symbol=symbol || "#";
let pattern = "";
for (let i = 0; i < gridSize/2; i++)
pattern += symbol + " ";//Forming the pattern
for (let i = 0; i < gridSize; i++) {
if (i % 2 === 0) {
console.log(pattern);
}
else {
console.log(" " + pattern) //For even rows adding the space in front
}
}
}
chessBoard('#',8);
let num = prompt("choose area of board"); // gets input to determine board size.
rowString = "";
for (let height = 0; height < num; height++){ // sets board height
for(let width = 0; width < num; width++){ // sets board width
if ((height+width) % 2 == 0){ // alternates chars by row & height position
rowString += "# ";
}
else{
rowString += " ";
}
}
rowString += "\n"; // after 'num' chars added to row, add new line to board
}
console.log(rowString);
The (height+row) % 2 == 0 on line 5 is important, as it determines whether it adds a " " or # to the rowString based on the height and row value. If it was just based on height you'd get alternating columns of #'s and " ", or if it was just based on width you'd get alternating rows of " " and #. If you consider the first point; height 0 width 0, it would evaluate even, height 1 width 1, odd etc.. next row height 1 width 0, odd etc... This ensures that your board is scalable.
Here's my own code
let size = 8;
let fill = '#'
let startWithSpace = true;
let addSpace = true ;
let board = '' ;
for(let i = 1; i <= size ; i++)
{
let row = '' ;
for(let column = 1; column <= size ; column++)
{
if(addSpace)
{
row += ' ' ;
addSpace = false ;
}
else
{
row += fill;
addSpace = true;
}
}
if(startWithSpace == true )
{
addSpace = false;
startWithSpace = false;
}
else
{
addSpace = true;
startWithSpace = true;
}
board+=row + "\n" ;
}
console.log(board)
Another one
let size = 16 ;
let fill = '#' ;
let space = " " ;
let board = ''
for(i = 1; i <= size ; i++)
{
for(c = 1; c <=size ; c++)
{
board += (i + c) % 2 == 0 ? space : fill ;
}
board += "\n" ;
}
console.log(board)
Here's my approach. I've added a detailed description in the JSDoc.
/**
* Eloquent JavaScript - Chapter 2 - Program Structure (Chessboard)
*
* x = 8
*
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
*
* Approach used:
*
* - If size of grid passed is 8, we'll have an 8x8 grid
* - Initialize an empty string
* - Loop through the grid size
* - If even iterator, start the row with a space, loop through (grid size - 1) and keep appending a '#'
* - If odd iterator, start the row with a '#', loop through (grid size - 1) and keep appending a space
* - After the inner loop finishes, we need to start a new line, so append '\n'
* - Once the loop has finished, we just return the result and that should be our required pattern
*
*
* #param x Size of grid being displayed
*
*/
function chessboard(sizeOfGrid) {
var result = ''
var charHash = '#'
var charSpace = ' '
var charNewLine = '\n'
var remainderSize = sizeOfGrid - 1
var i, j
for(i = 0; i < sizeOfGrid; i++) {
if(i%2 === 0) {
result += charSpace
for(j = 0; j < remainderSize; j++) {
if(j % 2 === 0) {
result += charHash
} else {
result += charSpace
}
}
} else {
result += charHash
for(j = 0; j < remainderSize; j++) {
if(j % 2 === 0) {
result += charSpace
} else {
result += charHash
}
}
}
result += charNewLine
}
return result
}
var result = chessboard(8)
console.log(result)
I have solved it using a Sting method called repeat()
Program goes as follows,
const pattern1 = ' #';
const pattern2 = '# ';
const binding = 4;
for(let i=1; i<9; i++){
if(i % 2 !== 0){
console.log(pattern1.repeat(binding));
}else{
console.log(pattern2.repeat(binding));
}
};
The output would be,
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Here's my approach:
const size = 8;
let board = "";
for (let i = 0; i < size; i++) {
board += `${(i % 2 === 0 ? " #" : "# ").repeat(size/2)}\n`;
}
console.log(board);
Here is my solution:
let before = '# '
let after = ' #'
let size = 8
for (let i = 1; i <= size; i++){
let pattern = ''
for(let x = 1; x <= size/2; x++){
if(i%2===0){pattern+= before}
else{pattern+= after}
}
console.log(pattern)
}