Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

arrays - How can I draw a cross in javascript

The aim is to write function drawACross which returns a cross shape with 'x' characters on a square grid of size and height of our sole input n. All non-'x' characters in the grid should be filled with a space character (" "). The arms of the cross must only intersect through one central 'x' character, and start in the corner of the grid, so for even values of n, return "Centered cross not possible!"

If n < 3, function should return "Not possible to draw cross for grids less than 3x3!" This is my code, but in the result the cross is not centered:

function drawACross(n) {
  if (n % 2 === 0) {
    console.log("Centered cross not possible!")
  } else if (n < 3) {
    console.log("Not possible to draw cross for grids less than 3x3!")
  } else {
    for (let i = 0; i < n; i++) {
      let arr = new Array(n)
      let y = arr.fill("", 0, arr.length)
      y.splice(arr.length - (i + 1), 1, "x")
      y.splice(i, 1, "x")
      console.log(y.join(" "))
    }
  }
}

drawACross(5);
question from:https://stackoverflow.com/questions/65951294/how-can-i-draw-a-cross-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of starting with empty strings and joining with a space, start with spaces and join with an empty string.

function drawACross(n) {
  if (n % 2 === 0) {
    console.log("Centered cross not possible!")
  } else if (n < 3) {
    console.log("Not possible to draw cross for grids less than 3x3!")
  } else {
    for (let i = 0; i < n; i++) {
      let arr = new Array(n)
      let y = arr.fill(" ", 0, arr.length)
      y.splice(arr.length - (i + 1), 1, "x")
      y.splice(i, 1, "x")
      console.log(y.join(""))
    }
  }
}

drawACross(5);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...