Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Last active June 11, 2018 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BideoWego/1007d649e7a4f3341d49afab8edabe8b to your computer and use it in GitHub Desktop.
Save BideoWego/1007d649e7a4f3341d49afab8edabe8b to your computer and use it in GitHub Desktop.
2D array utility functions
/**
* Creates and returns a 2D array range from the source array
* @param {Array} array - The source array
* @param {number} y - The y position from which to start the range
* @param {number} x - The x position from which to start the range
* @param {number} h - The height of the range
* @param {number} w - The width of the range
* @returns {Array} The selected range
*/
function range2d(array, y, x, h, w) {
const range = [];
for (let i = y; i < y + h; i++) {
const row = array[i];
const segment = [];
for (let j = x; j < x + w; j++) {
const value = row[j];
segment.push(value);
}
range.push(segment);
}
return range;
}
/**
* Creates and returns all the possible 2D array ranges from the source array
* @param {Array} array - The source array
* @param {number} h - The height of the range
* @param {number} w - The width of the range
* @returns {Array}
*/
function ranges2d(array, h, w) {
const ranges = [];
if (h <= 0 || h > array.length) {
return ranges;
}
if (w <= 0 || w > array[0].length) {
return ranges;
}
for (let y = 0; y <= array.length - h; y++) {
const row = array[y];
for (let x = 0; x <= row.length - w; x++) {
const range = range2d(array, y, x, h, w);
ranges.push(range);
}
}
return ranges;
}
/**
* Extracts values from a 2D array given a 2D pattern. Values are returned as a
* flattened array where values are placed in the order they were extracted,
* top to bottom, right to left
* @param {Array} pattern - The pattern array
* @param {Array} array - The source array
* @returns {Array} The extracted values
*/
function extract2d(pattern, array) {
const values = [];
for (let y = 0; y < pattern.length; y++) {
const row = pattern[y];
for (let x = 0; x < row.length; x++) {
const placeholder = row[x];
if (placeholder) {
values.push(array[y][x]);
}
}
}
return values;
}
// Run examples
if (require.main === module) {
const array = [
[0, 1, 2],
[2, 1, 0],
[1, 2, 3],
[3, 2, 1]
];
const ranges = ranges2d(array, 3, 2);
console.log(ranges);
const extracted = extract2d([
[ , 1, ],
[ , 1, ],
[ , 1, ]
], array);
console.log(extracted);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment