I need help. There is an object. I want to create a new array which will contain paired elements from groupOne and one element from groupTwo. Trick is that a1 cannot be paired with a2, and b1 cannot be paired with b2... You get the point.
let groups = {
groupOne: [ a1, b1, c1, d1 ],
groupTwo: [ a2, b2, c2, d2 ],
}
Final goal is to get array like this
pairs = [
[a1, c2],
[c1, d2],
[b1, a2],
[d1, b2]
]
The code below is my attempt. Idea is when there are two different indexes, move chosen element from both arrays (groupOne and groupTwo) to the end of array and remove them. First problem is when index === groupTwoRandomIndex. Second problem is after few iterations c1 and c2 are picked.
let pairs = groups.groupOne.map((team, index, arr) => {
let groupTwoRandomIndex = Math.floor(Math.random() * groups.groupTwo.length)
if (index !== groupTwoRandomIndex ){
let temp
groups.groupOne.push(groups.groupOne.splice(index, 1)[0])
groups.groupTwo.push(groups.groupTwo.splice(groupTwoRandomIndex, 1)[0])
temp = [arr[groups.groupOne.length], teams.unseeded[groups.groupTwo.length]]
groups.groupOne.pop()
groups.groupTwo.pop()
}
})
CodePudding user response:
I have written a solution which does what your statement says. I have assumed that we cannot pick an element twice.
Note that there can be multiple solutions to this problem.
let groups = {
groupOne: ["a1", "b1", "c1", "d1"],
groupTwo: ["a2", "b2", "c2", "d2"]
};
let pairs = [];
let alreadySelected = {};
const maximum = groups.groupTwo.length - 1;
const minimum = 0;
for (let i = 0; i < groups.groupOne.length; i ) {
let randomnumber =
Math.floor(Math.random() * (maximum - minimum 1)) minimum;
while (randomnumber === i || alreadySelected[groups.groupTwo[randomnumber]]) {
randomnumber =
Math.floor(Math.random() * (maximum - minimum 1)) minimum;
}
pairs.push([groups.groupOne[i], groups.groupTwo[randomnumber]]);
}
console.log("Pairs ", pairs);
CodePudding user response:
Relatively easy solution with map, as you can just zip
the array.
let groups = {
groupOne: [ "a1", "b1", "c1", "d1" ],
groupTwo: [ "a2", "b2", "c2", "d2" ],
}
console.log(groups.groupOne.map((elem, index) => [elem, groups.groupTwo[index]]))