Creating a hexagon pattern within an array

I'm in need of assistance in writing a function that can generate a hexagon pattern within a 2D array. I only have the column size of the array, and the rest of the dimensions must be calculated.

https://i.sstatic.net/WHuYF.png

Unfortunately, I'm facing difficulties with the mathematical aspects required for this task.

This is the code I've managed to come up with so far:

function deg2rad(degrees) {
  const pi = Math.PI;
  return degrees * (pi / 180);
}

function getCos(deg) {
  return Math.cos(deg2rad(deg));
}


function drawHexagon(cols) {
  // upper left corner
  const rows = parseInt(cols * getCos(30), 10);

  const arr = [...Array(rows)].map(() => Array(cols).fill(''));
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (j > Math.floor(cols / 4) - 1 && j < (cols - Math.round(10 / 4))) { // middle section (square)
        arr[i][j] = 1;
        continue;
      }

      if (i < Math.floor(rows / 2)) { // top half

        if (j < Math.floor(cols / 4)) { // left side (triangle)
          if (rows / 2 / (i + 1) < cols / 4 / (cols / 4 - j)) { // seems to be right
            arr[i][j] = 2;
          }
        } else { // right side (triangle)
          if (rows / (i + 1) < cols / (j / 4 + 1)) { // wrong
            arr[i][j] = 2;
          }
        }
      } else { // bottom half

        if (j < Math.floor(cols / 4)) { // Left side
          if (rows / (i + 1) > cols / 4 / (j + 1)) { // seems to be right
            arr[i][j] = 2;
          }
        } else { // bottom right 
          if (rows / 2 / (i + 1) > cols / 4 / (cols - j)) { // wrong
            arr[i][j] = 2;
          }
        }
      }
    }
  }
  console.log(arr); // console.table() not available in snippet
  return arr;
}
drawHexagon(8)

Upon outputting the array, the result appears as depicted here:

https://i.sstatic.net/GcQKT.jpg

It seems like the left side and middle section are correct.

I would greatly appreciate any help in solving this matter.

Answer №1

One of the challenges is the potential for slight discrepancies in the output of Math.sin () and Math.cos (), leading to instability in calculations due to floating point errors.

Another issue lies in the geometric calculations - specifically, the absence of accounting for the hypotenuse in the triangle, which is essential for ensuring a right angle triangle configuration.

https://i.sstatic.net/Eamyz.png

Potential Solution:

1- Begin by determining the length of side b, then calculate the hypotenuse (c) to validate the triangle's structure.

2- Verify if a²+b² = c²; if true, the sides (a, b, c) are valid, otherwise adjust to form a right angle triangle with the closest possible side lengths.

3- Transform the points into a 2D grid, resembling the depicted figure.

4- Establish connections between the points, aiming for efficiency by identifying the shortest path as the most direct route between them.

5- Finalize your grid with the calculated path values, assigning each cell the appropriate value based on the derived path array.

For more information on implementation details, refer to the provided JavaScript code link; note that the shortest path function remains under development.

Javascript-Code

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

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

Is it possible to hide a fixed header on scroll in a mobile device?

I am facing an issue with my Wordpress site where I want the header to hide when the user scrolls. Despite trying various codes, I have been unable to make it work. The reason for wanting to hide the header is that on mobile devices, it causes scroll prob ...

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...

Vue: downloading a file straight to your browser with the download attribute

I'm having an issue with axios where I am trying to download both a PDF and an image file. The image file downloads successfully and opens without any problems, but when I attempt to open the PDF file, it doesn't work as expected. downloadItem({ ...

The value for $routeParams.param appears to be undefined

I have set up a route and am attempting to send parameters to a controller: app.js .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('spot', { url: "/spot/:param", templateUrl: "templates/spot.html", ...

BufferGeometry-based Three.js mesh fails to display

Currently, I am in the process of developing a WebGL game using Three.js. In order to enhance performance, I have made the decision to transition from using THREE.Geometry to utilizing THREE.BufferGeometry. However, after making this change, I encountered ...

Properties around the globe with Express & Handlebars

Currently, I am utilizing Handlebars (specifically express3-handlebars) for templates and Passport for authentication in my NodeJS application. Everything is functioning smoothly, but I have been contemplating if there is a method to globally pass the req. ...

Automatically dismiss a Modal Popup without the need for a button or click event

I am currently facing an issue where I have a page constantly refreshing, and I am looking to implement a modal popup with a message saying "Please wait..." while the page reloads using $state.reload(). GenericModalService.confirmationSplit($rootScope, m ...

Is it possible to retrieve a JSON property using a string?

Here is the JSON I am working with: json_filter = {"CO": "blah"} I am attempting to access the member 'CO' using a string value, but the result keeps coming back as undefined. var selectedState = $(this).val(); // The state selected is 'C ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...

I am having trouble getting Form.Select to work in my basic react-bootstrap application, despite following the guidelines provided in the react-bootstrap documentation. Can

I am new to utilizing "react-bootstrap with hooks" and currently in the process of creating a basic form. I have been following the guidance provided by react-bootstrap documentation, but I encountered an issue specifically with select/option form elements ...

AngularJS IP Address masking

Looking for an IP address mask plugin that works with AngularJS. I attempted to use the "Jquery Input IP Address Control" plugin, but it wasn't functioning properly. The problem I encountered was that the "ngModel" attribute wasn't capturing the ...

Best practices for working with Angular, Laravel 4, and managing MySQL databases

I have recently started working with Angular and have some experience using Laravel 4. I am currently developing an application that allows users to edit on the go while also saving to a MySQL database. Originally, my plan was to use Angular for real-time ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

Nested function and the process of breaking out of the parent function

Is it possible to exit out of the main/parent function when I am in a function that was called from inside another function? For example: function(firstFunction(){ //stuff secondFunction() // code continuation if second function doesn't ...

Using NextJS to pass a parameter to an onClick function

I've been using the react-simple-star-rating package in this sample code. However, I'm facing an issue: Within my trains parameter, there is a variable id that I would like to pass to the handleRating function using onClick, but I can't see ...

What is the best way to visually highlight the selected item in a list with a special effect?

I have a list that I'd like to enhance by adding an effect to the selected item after a click event. For instance, after clicking on the first item 'Complémentaire forfait', I want to visually highlight it to indicate that it has been selec ...

Panoramic viewer for Three.js with multi-resolution image support

Is there a way to incorporate a three.js panorama viewer with multi-resolution images similar to pannellum? Check out pannellum's example here: . You can find the current code using three.js here:(//codepen.io/w3core/pen/vEVWML). Starting from an e ...

What is the best way to increase the size of an array in a PHP parent class

Is there a way to add elements to an array in a parent class in PHP without losing the existing data? Consider the following scenario: class ParentClass { $this->player = array( 'class' => array( 'basic' ...