Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
¿Cómo recopilar la intersección y ambos complementos de dos matrices dentro de una tarea?

arreglos-

 const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6];

Matrices vacías -

 const matches1 = []; const matches2 = []; const unmatches1 = [];

Círculo -

 for (const line of source) { const line2Match = target.find((line2) => { const isMatch = line === line2; return isMatch; }); if (line2Match) { matches1.push( line ); matches2.push(line2Match); } else { unmatches1.push(line); } }

Esta es la salida en este momento -

[ 1, 1, 1, 4 ] ​​​​​en partidos1

[ 3 ] ​​​en​​​​unmatches1

[ 1, 1, 1, 4 ] ​​​​​en partidos2

La salida deseada -

[ 1, 4 ] ​​​​​en ​​​​​​​partidas1

[ 1, 1, 3 ] ​​​​​en ​​​​​​​desigualdades1

[ 1, 4 ] ​​​​​en ​​​​​​​partidos2

Lo que me gustaría agregar es que cuando la source coincida con target , el valor se eliminará de la matriz de target , ¿cómo puedo lograrlo?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

El OP...

"Lo que me gustaría agregar es que cuando la fuente coincida con el destino, el valor se eliminará de la matriz de destino, ¿cómo puedo lograrlo?"

Uno tenía que mutar activamente la matriz de target cortando el elemento común de ella, lo que al final hace que target se convierta en el complemento relativo de la source en target ... comúnmente/vulgo... la diferencia del objetivo .

Una de las causas podría aplicar una copia superficial del target como parte del valor inicial de una tarea de reduce para no mutar la referencia del target original en sí ...

 function collectIntersectionAndComplements(collector, sourceItem) { const { targetDiff } = collector; const targetIndex = targetDiff .findIndex(targetItem => targetItem === sourceItem); if (targetIndex === -1) { // collect the relative complement of target // in source ... vulgo ... the source difference. (collector.sourceDiff ??= []) .push(sourceItem) } else { // collect the intersection of both source and target ... (collector.intersection ??= []) .push( // ... by rejecting the common item from the original // target, thus actively mutating the latter, which leads // to ending up additionally with the relative complement // of source in target ... vulgo ... the target difference. targetDiff.splice(targetIndex, 1)[0] ); } return collector; } const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; const { intersection, sourceDiff, targetDiff, } = source.reduce(collectIntersectionAndComplements, { targetDiff: [...target] }); console.log({ source, target, intersection, sourceDiff, targetDiff });
 .as-console-wrapper { min-height: 100%!important; top: 0; }

@ heyheyhey2 ... Por cierto, si uno estaba hablando de la teoría simple de conjuntos , entonces no se permitían valores duplicados (idénticos) dentro de cada matriz/lista/conjunto. Los conjuntos siempre tienen que presentar solo valores únicos.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solo para partidos 1: (similar para partidos 2)

 const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; let matches1 = source.reduce((res, curr) => { if (target.includes(curr) && !res.includes(curr)) { res.push(curr); } return res; }, [] ); console.log(matches1) //[1,4]

Para no coincidencias1:

 let unmatches1 = source.reduce((res, curr) => { if ((target.includes(curr) && res[0].includes(curr)) || !target.includes(curr)) { res[1].push(curr); } if (target.includes(curr)) { res[0].push(curr) } return res; }, [[],[]] )[1] console.log(unmatches1) //[1,1,3]

Para lograr el resultado de unmatches2 [2,5,6], simplemente reemplace la fuente y el destino en la entrada, o en el código, o extienda el código aunque tenga ambas salidas. Es simple.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Tenga en cuenta que para un solo paso, ambas matrices deben haberse clasificado en orden ascendente.

 function go(){ const a = [0,1, 1, 1, 3, 4, 6,8,10]; const b = [-3,-4,1, 2, 4, 5, 6,25,26]; let nomatcha=[]; let match=[]; let nomatchb=[]; let i=0,j=0; while(true){ if(i>=a.length){ for (;j<b.length;j++) nomatchb.push(b[j]); break; } else if (j>=b.length){ for (;i<a.length;i++) nomatcha.push(a[j]); break; } else if(a[i]==b[j]){ match.push(a[i++]); j++; } else if (a[i]<b[j]){ let val=a[i++]; if(nomatcha.length==0)nomatcha.push(val); else if(val != nomatcha[nomatcha.length-1]) nomatcha.push(val); } else if (b[j]<a[i]){ let val=b[j++]; if(nomatchb.length==0)nomatchb.push(val); else if(val != nomatchb[nomatchb.length-1]) nomatchb.push(val); } } console.log("match: "+match); console.log("nomatcha: "+nomatcha); console.log("nomatchb: "+nomatchb); }

}

Producción:

coincidencia: 1,4,6 nomatcha: 0,1,3,8,10 nomatchb: -3,-4,2,5,25,26

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda