Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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

like image 342
DigitalJohn Avatar asked Nov 14 '12 11:11

DigitalJohn


2 Answers

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.

like image 170
Asad Saeeduddin Avatar answered Sep 21 '22 09:09

Asad Saeeduddin


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
like image 41
georg Avatar answered Sep 24 '22 09:09

georg