Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
Eliminar elementos de la matriz para alcanzar una longitud fija - JavaScript

Estoy tratando de escribir una función de JavaScript que elimine elementos de una matriz para alcanzar una longitud definida. La función debe eliminar las "brechas" de manera uniforme a través de la matriz. Necesito esta función para simplificar los vértices de los polígonos para dibujar en lienzo.

Así es como debería funcionar:

ingrese la descripción de la imagen aquí

Este es el código que se me ocurrió:

 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 3 console.log(simplify([ { x: 10, y: 20 }, { x: 30, y: 40 }, { x: 40, y: 50 }, { x: 50, y: 60 } ], 3))

Sin embargo, esto solo parece funcionar a veces y el problema puede estar en las matemáticas. ¿Cuál es el algoritmo que puede lograr esto o qué estoy haciendo mal?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Tal vez esto ayude

Suponga que tiene una cadena de longitud n y desea que tenga una longitud m. Tiene n-2 elementos para elegir y m-2 elementos para elegir para su nueva matriz. Ahora, suponga que actualmente ha seleccionado i elementos y ha pasado j elementos. Si i/j < (m-2)/(n-2) entonces estás atrasado. Probablemente deberías tomar otro elemento. Lo que realmente quiere saber, para una selección máximamente uniforme, es si (i+1)/(j+1) o i/(j+1) está más cerca de su objetivo de (m-2)/(n-2) ). Si el desbordamiento no es un problema, puede hacer un poco de álgebra para determinar si esto es equivalente a si (i+1) (n-2) - (j+1) (m-2) es mayor o menor que ( n-2)/2; más significa que i es mejor (así que no tomes este), mientras que menos significa que i+1 es mejor.

about 4 years ago · Juan Pablo Isaza Report

0

Resolví esto de la misma manera que hago búsquedas de texturas del vecino más cercano. La variable de paso de coma flotante (mayor que cero) se eleva al siguiente índice inferior, pero cuando 'piso (i*paso)' es mayor que 'i', toma su primer salto.

 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));

De paso,

 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; }

es un filtro magnético bilineal, si alguna vez desea aumentar el conteo en lugar de disminuirlo. Esto podría bifurcarse si la longitud deseada ('vértices') es mayor que la 'array.length'. También es un algoritmo útil para el software de sintetizador de audio.

about 4 years ago · Juan Pablo Isaza Report

0

Si solo desea eliminar elementos para cortar esa matriz a la longitud deseada. Utilice la función Array.splice().

Entonces, si su desiredLength = 3 por ejemplo. Y tienes una array = [1,2,3,4,5] .

array.splice(0,desiredLength).length == desiredLength debe ser verdadero.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!