简体   繁体   中英

'Crop' a two dimensional array?

Im looking for a highly performant way to crop a two dimensional array. Consider this example:

I have a two dimensional array that makes up a 100x100 grid. I just want to return just a crop of it, 60x60. Here is an example of 'a' way to do it, but am looking for pointers to the most performant way of doing this.

// Settings
var gridWidth = 100;
var gridHeight = 100;

// Populate Grid
var grid = [];

for(var i = 0; i<gridWidth; i++){
    grid[i] = [];
    for(var j = 0; j<gridHeight; j++){
        grid[i][j] = 0;
    }
}

// Crop Grid
var rect = {x:20,y:20,w:60,h:60};

var crop = [];
for(var i = rect.x; i<rect.x+rect.w; i++){
    crop[i-rect.x] = [];
    for(var j = rect.y; j<rect.y+rect.h; j++){
        crop[i-rect.x][j-rect.y] = grid[i][j];
    }
}

Any thoughts greatly appreciated...

John

Try it this way:

crop = grid.slice(rect.x, rect.x+rect.w);
for(var i = 0; i<crop.length; i++){
    crop[i] = crop[i].slice(rect.y, rect.y+rect.h);
}

Note that the dimensions of the array are now rect.w x rect.h , and all indices are negatively offset by rect.x and rect.y respectively.

How about:

function tab(n, func) {
    for (var a = [], i = 0; i < n; i++)
        a.push(func(i));
    return a;
}

function matrix(w, h, values) {
    return tab(h, function(y) {
        return tab(w, function(x) {
            return values(x, y);
        })
    })
}

grid = matrix(7, 10, function(x, y) {
    return x + ':' + y;
})

this gives us:

0:0 1:0 2:0 3:0 4:0 5:0 6:0
0:1 1:1 2:1 3:1 4:1 5:1 6:1
0:2 1:2 2:2 3:2 4:2 5:2 6:2
0:3 1:3 2:3 3:3 4:3 5:3 6:3
0:4 1:4 2:4 3:4 4:4 5:4 6:4
0:5 1:5 2:5 3:5 4:5 5:5 6:5
0:6 1:6 2:6 3:6 4:6 5:6 6:6
0:7 1:7 2:7 3:7 4:7 5:7 6:7
0:8 1:8 2:8 3:8 4:8 5:8 6:8
0:9 1:9 2:9 3:9 4:9 5:9 6:9

The crop function:

function crop(mat, x, y, w, h) {
    return mat.slice(y, y + h).map(function(row) {
        return row.slice(x, x + w)
    })
}

cropped = crop(grid, 2, 1, 5, 6)

result:

2:1 3:1 4:1 5:1 6:1
2:2 3:2 4:2 5:2 6:2
2:3 3:3 4:3 5:3 6:3
2:4 3:4 4:4 5:4 6:4
2:5 3:5 4:5 5:5 6:5
2:6 3:6 4:6 5:6 6:6

You can try to use Array#slice [MDN] and see whether you gain any performance improvements. Also try to avoid unnecessary computations:

var yend = rect.y + rect.h;
var crop = [];

for(var i = rect.x, j = 0, l = rect.x + rect.w; i < l; i++,j++){
    crop[j] = grid[i].slice(rect.y, yend);
}

You could test if it is worth to test for edge cases. For example, if rect.x and/or rect.y are 0 and you don't need the original array anymore, you can just set the .length of the array(s) (which modifies them):

var rect = {x:0,y:0,w:60,h:60};

grid.length = rect.w;

for (var i = 0; i < rect.w; i++) {
    grid[i].length = rect.h;
}

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