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

102
Vistas
Randomly swap 2 elements of array with another 2 elements

I have a list of team members and a list of 2 substitutes: team = Samson, Max, Rowan, Flynn, Jack subs = Struan, Harry

I need to randomly swap the 2 subs into the team. I'm getting stuck because I need to ensure that only these 2 elements are swapped and that both are swapped in. I tried just looping through the subs array and randomly swapping each element with an element from the team array, but too frequently it swapped Struan with Max and then Harry with Struan, so that in the end Struan was still in the subs array and not in the team.

So: I need to exclusively swap the 2 elements in the sub array with random elements from the team array. How can I do that?

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

0

You can do this with this function. Give the function current team and substitudes and get new team with random substitution done.

const team = ['Samson', 'Max', 'Rowan', 'Flynn', 'Jack']
const subs = ['Struan', 'Harry']

const substitudePlayers = (team, subs) => {
  const newTeam = [...team]
  // get 2 random numbers which are less than team members count
  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max-1);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  // 2 random numbers
  let num1 = getRandomInt(0, team.length)
  let num2 = getRandomInt(0, team.length)
  
  // make sure that numbers are different
  while(num2 === num1) num2++
  
  // substitude
  newTeam[num1]=subs[0]
  newTeam[num2]=subs[1]
  return newTeam
}

const substitudedTeam = substitudePlayers(team, subs);

console.log(substitudedTeam)

about 4 years ago · Juan Pablo Isaza Denunciar

0

This should work:

function getRandomItem () {
   let randomItem = team[Math.floor(Math.random()*team.length)];
   if(subs.indexOf(randomItem)<0){
      return randomItem;
   } else {
      return getRandomItem();
   }
}

subs.forEach((item,i)=>{
   subs.splice(i,1,getRandomItem());
}
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