首先为标题道歉,我不知道它是否描述了我想要实现的目标,但它是我所拥有的最好的。
基本上我有一个数组来描述二维空间的强度。然后我想在给定的一组迭代中将此强度分配给邻居,即假设我有以下数组:
intensity = [ 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 100, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0 ]
然后我对我的distributeIntensity算法进行一次传递(将50%的强度分配给邻居)。然后我会有:
[ 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 50, 50, 50, 0,
0, 50, 100, 50, 0,
0, 50, 50, 50, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0 ]
如果我对原始数组进行 2 次传递,我的结果数组将是:
[ 0, 0, 0, 0, 0,
25, 50, 75, 50, 25,
50, 150, 200, 150, 50,
75, 200, 300, 200, 75,
50, 150, 200, 150, 50,
25, 50, 75, 50, 25,
0, 0, 0, 0, 0 ]
我目前的代码是:
this.distributeIntensities = function(passes, shareRatio) {
for (var i = 0; i < passes; i++) { this.distributeIntensity(shareRatio); }
}
this.distributeIntensity = function(shareRatio) {
var tmp = hm.intensity.slice(0); // copy array
for (var i = 0; i < tmp.length; i++) {
if (hm.intensity[i] <= 0) { continue; }
var current = hm.intensity[i];
var shareAmount = current * shareRatio;
this.shareIntensityWithNeighbours(tmp, shareAmount, i);
}
hm.intensity = tmp;
}
this.shareIntensityWithNeighbours = function(arr, heat, i) {
// This should be var x = Math.floor(...) however
// this is slower and without gives satisfactory results
var x = i % hm.columnCount;
var y = i / hm.columnCount;
if (x > 0) {
if (y > 0) arr[i - hm.columnCount - 1] += heat;
arr[i - 1] += heat;
if (y < (hm.rowCount - 1)) arr[i + hm.columnCount - 1] += heat;
}
if (y > 0) arr[i - hm.columnCount] += heat;
if (y < (hm.rowCount - 1)) arr[i + hm.columnCount] += heat;
if (x < (hm.columnCount - 1)) {
if (y > 0) arr[i - hm.columnCount + 1] += heat;
arr[i + 1] += heat;
if (y < (hm.rowCount - 1)) arr[i + hm.columnCount + 1] += heat;
}
}
现在,这可行,但是速度很慢(我正在处理一个巨大的数组和 8 次传球)。我知道有一种更快/更好/更清洁的方法,但这超出了我的能力范围,所以我把它放在那里,希望有人能指出我正确的方向(注意:事实上,我不会说流利的数学我在数学上相当文盲)。
提前致谢
圭多