Home > Net >  I'm creating a 2D array in Javascript. How do I skip creating a part of it?
I'm creating a 2D array in Javascript. How do I skip creating a part of it?

Time:07-17

What I'm doing: I need to create a ~400x400 grid of waypoints. I have the coordinates. Each waypoint is 9 blocks from the previous. Each waypoint is its own file.

The issue: There's a ~100x100 hole in the grid. Those waypoints should not be created. I divided the issue into 4 rectangles and created loops for each of them. It works, but it's an ugly solution. Someday, it might have to do be for something more serious than a game and could me more complex than this.

How do I do it in one loop? The solution probably lies in using some AND or NOT while declaring the loops. Please, advise.

There might also be a different approach to the problem. A different solution I hadn't thought of. Feel free to suggest.

Here's the code up to the first loop. The other three are practically copy-paste.

fs = require('fs');

const xWest = -7113;
const xEast = -6744;
const zNorth = -10265;
const zSouth = -9896;
const wallxWest = -6993;
const wallxEast = -6864;
const wallzNorth = -10145;
const wallzSouth = -10016;

var currentX = 0;
var currentZ = 0;

//The first loop:
for (currentX = xWest; 
    currentX < wallxWest; 
    currentX = currentX   9) 
    {
        for (currentZ = zNorth; 
            currentZ < zSouth; 
            currentZ = currentZ   9) {
              fs.writeFile(`...${currentX-xWest}_${currentZ-zNorth}.json`,
              `file_contents_here`
              ,function (err){if (err) return console.log(err);
              });
    }};

CodePudding user response:

I got it. That "different approach" part.

  1. create an array in the code and set the middle to an unused value
  2. for each non-unused value, make a file.

Edit: fixed the original code. Wrapped "write file" in an "if within range".

for (currentX = xWest 4;
  currentX < xEast 4;
  currentX = currentX   9) {
  for (currentZ = zNorth 4;
    currentZ < zSouth 4;
    currentZ = currentZ   9) {
      if (
        ((currentX < wallxWest) || (currentX > wallxEast)) && ((currentZ < wallzNorth) || (currentZ > wallzSouth)))
      {
      fs.writeFile(`...${currentX - 4 - xWest}_${currentZ - 4 - zNorth}.json`,
      //file contents removed for code readability
      , function (err) { if (err) return console.log(err); });
    }
  }
};
  • Related