I am trying to write a JavaScript function that removes items from an array to reach a defined length. I need this function to simplify polygon vertices for canvas drawing.
This is how it should work:
The function should eliminate the "gaps" evenly through the array. This is the code I came up with:
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!
simplify([{x: 10, y: 20}, {x: 30, y: 40}, ...], 30); // The result should be an array with the length of 30
However, this only seems to work sometimes and the problem may be in the math. If someone knows of an algorithm that can achieve this or can tell me what I am doing wrong it would be greatly appreciated. Thanks in advance!
CodePudding user response:
Maybe this will help
Suppose you have a string of length n, and you want it to be length m. You have n-2 elements to pick from, and m-2 elements to pick for your new array. Now, suppose you have currently picked i elements and have passed j elements. If i/j < (m-2)/(n-2) then you are behind. You probably ought to take another element. What you really want to know, for a maximally even selection, is whether (i 1)/(j 1) or i/(j 1) is closer to your target of (m-2)/(n-2). If overflow isn't a problem, you can do a little algebra to figure out that this is equivalent to whether (i 1)(n-2) - (j 1)(m-2) is more or less than (n-2)/2; more means i is better (so don't take this one), while less means i 1 is better.
CodePudding user response:
If you just want to eliminate items to cut that array to a desired length. Use the Array.splice() function.
So if your desiredLength = 3
for example. And you have an array = [1,2,3,4,5]
.
array.splice(0,desiredLength).length == desiredLength
should be true.