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?
CodePudding user response:
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());
}
CodePudding user response:
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)