我正在嘗試撰寫一個 JavaScript 函式,該函式從陣列中洗掉專案以達到定義的長度。我需要這個函式來簡化畫布繪制的多邊形頂點。
這是它應該如何作業:

該函式應該通過陣列均勻地消除“間隙”。這是我想出的代碼:
function simplify(array, vertices) {
// Calculate gap size
var gap = array.length - vertices;
gap = Math.floor(array.length / gap);
var count = 0;
var result = [];
// Fill a new array
for (var i = 0; i < array.length; i ) {
if (count == gap) {
count = 0;
} else {
result.push(array[i]);
count ;
}
}
// Eliminate 1 item in the middle if length is odd
if (result.length > vertices) {
result.splice(Math.floor(result.length / 2), 1);
}
return result;
}
// This gives the wrong result depending on the length of the input!
// The result should be an array with the length of 30
console.log(simplify([
{ x: 10, y: 20 },
{ x: 30, y: 40 },
{ x: 40, y: 50 },
{ x: 50, y: 60 }
], 3))
然而,這似乎只是有時有效,問題可能出在數學上。如果有人知道可以實作這一點的演算法,或者可以告訴我我做錯了什么,將不勝感激。提前致謝!
uj5u.com熱心網友回復:
也許這會有所幫助
假設您有一個長度為 n 的字串,并且您希望它的長度為 m。您有 n-2 個元素可供選擇,還有 m-2 個元素可供您選擇新陣列。現在,假設您當前選擇了 i 個元素并傳遞了 j 個元素。如果 i/j < (m-2)/(n-2) 那么你就落后了。您可能應該采用另一種元素。對于最大均勻選擇,您真正想知道的是 (i 1)/(j 1) 或 i/(j 1) 是否更接近您的目標 (m-2)/(n-2 )。如果溢位不成問題,你可以做一點代數計算,這等價于 (i 1) (n-2) - (j 1) (m-2) 是大于還是小于 ( n-2)/2; 更多意味著 i 更好(所以不要選擇這個),而更少意味著 i 1 更好。
uj5u.com熱心網友回復:
如果您只想消除專案以將該陣列切割為所需的長度。使用 Array.splice() 函式。
所以如果你desiredLength = 3的例子。你有一個array = [1,2,3,4,5].
array.splice(0,desiredLength).length == desiredLength 應該是真的。
uj5u.com熱心網友回復:
我以與最近鄰紋理查找相同的方式解決了這個問題。浮點步長變數(大于零)被下限到下一個較低的索引,但是當 'floor(i*step)' 大于 'i' 時,它會進行第一次跳轉。
function simplify(array, vertices){
vertices = vertices || 1;///No div by zeros please :)
var result = [];
var step = array.length/vertices;
for(var i=0;i<vertices;i ){
result.push(array[Math.floor(step*i)]);
}
return result;
}
//Testing it out
var testarr = [];
for(var ai=0;ai<51;ai ){
testarr[ai] = {
x:ai,
y:10*ai
}
}
console.log(testarr.slice(0));
var ret = simplify(testarr, 29);
console.log(ret.slice(0));
順便,
function simplify_bilinear(array, vertices){
var result = [];
var step = array.length/vertices;
for(var i=0;i<vertices;i ){
var fistep = Math.floor(i*step);//The nearest neighbor index
var current = array[fistep];//This element
var next = array[fistep 1];//The next element
var mix = (i*step)-fistep;//The fractional ratio between them. As this approaches 1, the mix approaches the next value.
//mix = mix * mix * (3 - 2 * mix);//Optional (s-curve) easing between the positions. Better than linear, anyway.
//Alternately to the above//mix = Math.sin((mix*2 - 1)*Math.PI)*.5 .5;///for a sinusoid curve
//True Bezier would be optimal here but beyond this scope
var mixed_point = {
x:current.x (next.x-current.x)*mix,//basic mixing, ala 'mix' in your average math library
y:current.y (next.y-current.y)*mix,
}
result.push(mixed_point);
}
return result;
}
是一個雙線性磁過濾器,如果你想增加計數而不是降低它。如果所需長度('頂點')大于'array.length',這可能會發生分支。也是軟體音頻合成器的有用演算法。
快樂編碼:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368451.html
標籤:javascript 数组 数学 帆布 几何学
下一篇:如何挑出矩陣中的特定值[R]
