简体   繁体   中英

How to find all elements between two coordinates in a 2d array

Essentially I'm trying to create the game reversi. To cut it short if you don't know what it is, I have a 8x8 board of squares. There are 2 coordinates and I need to determine all the squares that are between the two coordinates and fill them in. The 2 coordinates are either on the same y, same x or diagonal to each other.

Can someone explain the logic behind how I would go about doing something like this? How can I determine the coordinates of all the elements between the 2 coordinates.

You need a simple for loop, starting at one of the coordinates and moving towards the other.

 let connect = (c1, c2) => { // Determine the distance between c1 & c2 let delta = c1.map((v, i) => c2[i] - v); let distance = Math.max(...delta.map(v => Math.abs(v))); // Determine the unit vector (eg [1, -1]) to move each iteration let direction = delta.map(v => v / distance); // Starting at `c1`, iterate for `distance` iterations, moving in `direction` each iteration. return [...Array(distance + 1)].map((_, i) => c1.map((v, j) => v + direction[j] * i)); // Same as above, but exclude `c1` and `c2` from the return array. // return [...Array(distance - 1)].map((_, i) => c1.map((v, j) => v + direction[j] * (i + 1))); }; let c1 = [3, 6]; let c2 = [8, 1]; console.log(connect(c1, c2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM