It's not entirely clear to me how you came to your current implementation, but I can at least tell:
- β
You correctly determined the size of the sub grid array to return (
kWH) - β You incorrectly assume you can slice out a sub grid as one continuous part of the original 1d array
- π The calculation of the first element seems kind-of-right but is actually wrong (probably because of the previous mistake)
Let's start from scratch and work our way up to a nice one liner.
In a 2d-array, you can get a cell's value by doing:
cellValue = grid2d[y][x]
Once you flatten it, you'll need to do:
cellValue = grid1d[y * GRID_W + x]
As you can see, you need to know the original grid's size before you can even query a specific cell. That means your extract function would need an argument to pass the original width (or, if the grids are guaranteed to be square, you can do Math.sqrt(array.length).
Let's use this math to find the indices of a 2x2 sub grid at (1,1) extracted from a 3x3 source grid:
1: A 2: B 3: C
4: D 5:[E] 6:[F]
7: G 8:[H] 9:[I]
As you can see, the resulting indices are [5,6,8,9]. There is no way to slice these indices out of the source array directly.
Instead, we can use a nested loop to skip the gaps between our rows:
const to1d = (x, y, w) => y * w + x;
const extractSubGrid1D = (grid, gridWidth, x, y, w, h) => {
const yStart = y;
const yEnd = y + h
const xStart = x;
const xEnd = x + w;
const subgrid = [];
for (let y = yStart; y < yEnd; y += 1) {
for (let x = xStart; x < xEnd; x += 1) {
const index = to1d(x, y, gridWidth);
subgrid.push(grid[index]);
}
}
return subgrid;
}
const originalGrid = [
1, 2, 3,
4, 5, 6,
7, 8, 9
];
console.log(
extractSubGrid1D(originalGrid, 3, 1, 1, 2, 2)
)
Once you get a feel for the logic, feel free to refactor.
To go from a 1d-index to a 2d coordinate, you can do:
x = i % w
y = Math.floor(i / w)
Applying this logic, you can also fill your sub grid like so:
const to1d = (x, y, w) => y * w + x;
const extractSubGrid1D = (grid, gridWidth, x, y, w, h) => Array.from(
{ length: w * h },
(_, i) => grid[ to1d(x + i % w, y + Math.floor(i / h), gridWidth) ]
)
const originalGrid = [
1, 2, 3,
4, 5, 6,
7, 8, 9
];
console.log(
extractSubGrid1D(originalGrid, 3, 1, 1, 2, 2)
)
- 23.5k
- 4
- 33
- 49