2016-11-11 87 views
0

我有包含與x座標,y座標,和值的子陣列用於矩陣的陣列的有效方法:用於將線性陣列以矩陣

// [x,y,value] 
var arr = [ 
[1,2,0.01], 
[1,3,0.02], 
[1,4,0.05], 
[1,5,0.03], 
[2,3,0.04], 
[2,4,0.02], 
[2,5,0.01], 
[3,4,0.06], 
[3,5,0.05], 
[4,5,0.07], 
] 

然後,我有一個零填充的2D陣列( 「矩陣」)x_max×x_max維度。我試圖用一個計算有效的方法來填補這個矩陣的值如下:

// already have a variable called 'matrix' which is zero-filled 

function constructMatrix(){ 
    for(var i in arr){ 
     var y = arr[i][0]; 
     var x = arr[i][1]; 
     var val = arr[i][2]; 
     matrix[y][x] = val; 
    } 
} 

什麼,我得到的是具有獨特的列值的矩陣,但跨行相同的值。在我的邏輯中有沒有簡單的中斷?

我希望類似以下的輸出:

var matrix = [ 
[0.01,0.02,0.05,0.03], 
[0,0.04,0.02,0.01], 
[0,0,0.06,0.05], 
[0,0,0,0.07], 
] 
+2

您能給我們一個預期輸出的例子嗎? –

+0

@kevinternet你在那裏。 – Wagtail

+0

這是一個問題的小提琴:https://jsfiddle.net/ocwna691/ – Wagtail

回答

2

你可以這樣說:

var arr = [ 
 
    [1, 2, 0.01], [1, 3, 0.02], [1, 4, 0.05], [1, 5, 0.03], 
 
    [2, 3, 0.04], [2, 4, 0.02], [2, 5, 0.01], [3, 4, 0.06], 
 
    [3, 5, 0.05], [4, 5, 0.07] 
 
]; 
 

 
// find total number of rows and columns 
 
// add 1 because (x = 5) == (index 6) // indexes start at 0 
 
var rows = arr.reduce((x,y) => Math.max(x, y[0]), 0) + 1; 
 
var columns = arr.reduce((x,y) => Math.max(x, y[1]), 0) + 1; 
 

 
// initiate an empty matrix 
 
var matrix = [...Array(rows)].map(() => Array(columns).fill(0)); 
 

 
// loop over the points 
 
arr.forEach(function(point) { 
 
    var x = point[0]; 
 
    var y = point[1]; 
 
    var val = point[2]; 
 
    matrix[x][y] = val; 
 
}); 
 

 
// your result 
 
console.log( JSON.stringify(matrix, 0, 2) );
.as-console-wrapper { 
 
    max-height: 100%!important; 
 
}

+0

很優雅!比我所做的更好,加上它的作品!謝謝。 – Wagtail

1

如果座標(1,2)你的意思是第一列,第二行那麼你應該做

matrix[y - 1][x - 1] = val 

因爲座標從0,0開始並在4,4(對於5x5矩陣)完成

+0

這是我需要做的事,正確的,但如果我在小提琴中替換它,我仍然會遇到同樣的問題(但現在使用正確的座標)。 – Wagtail