What is the best way to create a cross shape using JavaScript?

To achieve the desired outcome, the task is to create a function called drawACross. This function should generate a cross shape consisting of 'x' characters on a square grid. The size and height of the grid are determined by a single input parameter, n. Any empty spaces in the grid should be represented by space characters (" ").

The arms of the cross must intersect at a single central 'x' character, starting from the corners of the grid. If the value of n is even, the function should return

"Centered cross not possible!"
.

If n < 3, the function should output

"Not possible to draw cross for grids less than 3x3!"
.

Below is an example code snippet that attempts to implement this functionality:

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);

Answer №1

To optimize the process, consider starting with spaces and combining them using an empty string instead of beginning with empty strings and then merging them with a space.

function drawACross(n) {
  if (n % 2 === 0) {
    console.log("Drawing a centered cross is not possible!")
  } else if (n < 3) {
    console.log("It is impossible to draw a cross for grids smaller 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);

Answer №2

To simplify the process, you could opt to construct a string character by character rather than using a more efficient method. A key observation is that for a diagonal cross pattern, the characters marked are those where the X and Y coordinates are equal (and also mirror each other).

function drawACrossPattern(size) {
  if (size % 2 === 0) {
    console.log("Creating a centered cross is not possible!");
    return;
  }
  if (size < 3) {
    console.log("Cross patterns cannot be drawn for grids smaller than 3x3!");
    return;
  }
  for (let y = 0; y < size; y++) {
    let line = "";
    for (let x = 0; x < size; x++) {
      line += x == y || x == size - 1 - y ? "x" : " ";
    }
    console.log(line);
  }
}

drawACrossPattern(5);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

web browser display size

Encountering a challenge here. My approach involves: Loading 3 html pages consecutively inside webview on android and then trying to obtain the height of each page. webview.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT"); //we ...

Connecting a menu item with content in iView

I am currently working on developing an administrator console for my Android game. This console is being built as a single page web application with the help of Vue.js and iView. The main page features an iView side navigation bar with various menu items. ...

Arrange an array of strings in which the elements follow the format "Name:Score"

I am currently working with a string array that is stored in LocalStorage. Within this array, each element follows the format "Name:Score". My goal is to sort this array by score in order to create a leaderboard. How can I efficiently achieve this? Perhap ...

Using PHP's Laravel framework to manipulate arrays, export data to Excel

I've encountered a small issue where I have an array parsed from Excel tables. The first element represents the attribute and the second element represents the value. My goal is to convert it into pretty JSON format, specifically on line 32 where &apo ...

Combining arrays of objects and converting them into a JSON array using Javascript

I struggle to seamlessly merge all the necessary transformations. I would greatly appreciate some assistance from those who are more comfortable with data manipulation, thank you. Here is a visual representation of my objective: [ [ { ...

How should you go about including an optional parameter in a function that currently only has one parameter?

I have a function that I need to use in an onClick action as well as other parts of the code. I am attempting to create an optional parameter that returns a class object instead of a false value. import $ from 'jquery' const test = (optionalParam ...

Changing the name of a checkbox label using jQuery and JavaScript

I am struggling with dynamically creating checkboxes and setting the label names correctly. Setting the inner html value didn't work for me. What is the proper way to achieve this? source: <!DOCTYPE html> <html> <head> ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

Enhance each category changing with jQuery page transitions

Is there a way to add page transitions based on category names and quantities in PHP? For example, when clicking on the "office" category, can a popup overlay be displayed with the category name and quantity while the content loads? The focus is on creat ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

Guide on converting FormData, an HTML5 object, to JSON

Is there a way to transform the data from an HTML5 FormData object into JSON format? I'm specifically looking for a solution that does not rely on jQuery, and that only serializes the key/value pairs of the FormData object. ...

Integrate a new column into a 2D array by assigning values from a second 2D array through mapping, or use a default value of zero when necessary

I am looking for a way to combine data from two 2d arrays by matching values in the ID column. When transferring NUM values from the second array to the first array, I want to default the value to 0 if there is no corresponding row. $array1 = [ [' ...

Socket.io connects two clients together in a room

Currently, I am working on integrating private messaging functionality into an app I am developing using express 3 and socket.io. Upon a client connection, a room is automatically created and joined based on the client's user id. This feature serves ...

When the LI element is clicked, it triggers the display of another LI element without affecting the rest of the

New to the web development scene and trying to figure out how to create a collapsible text feature using HTML, JavaScript, and JQuery. I've got the styling down but struggling with the scripting part. Here's an example of what I'm trying to ...

Guide on showcasing an alert notification when the data is already existing within an array through javascript

Need help with displaying an alert message in JavaScript for duplicate values in an array? var names = []; var nameInput = document.getElementById("txt1"); var messageBox = document.getElementById("display"); function insert() { names. ...

Finding the exact time zone utilizing AngularJS

Is it possible to retrieve the PC's Time Zone using Angular? I specifically need the timezone in the format of '+H:MM' for manipulation. I know that Angular typically formats time zones as '+HHMM', so my goal is to store this time ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Is it possible for me to ensure that the argument passed to `res.write` is sent as one solid chunk?

When utilizing express' res.write method to send chunks back to the requestor, it is important to note that one call to res.write does not necessarily mean the argument passed will be received as a single chunk. This can complicate the process of pars ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...