Untitled
unknown
javascript
2 years ago
1.7 kB
13
Indexable
const players = [ { name: 'Anna', score: 1 }, { name: 'Bartek', score: 2 }, { name: 'Cezary', score: 1 }, { name: 'Dawid', score: 1 }, { name: 'Ewa', score: 1 }, { name: 'Asia', score: 1 }, { name: 'Kasia', score: 2 }, { name: 'Basia', score: 1 }, { name: 'Wojtek', score: 0 }, { name: 'Tomek', score: 0 } ]; const playerBye = {name: 'BYE', score: 0} const getRandomByGroup = (group) => { const random = Math.floor(Math.random() * group.length) const result = group.splice(random, 1) return result[0] } players.sort((a, b) => b.score - a.score) const pointGroups = [] for (let i = 0; i < players.length; i++) { const player = players[i]; pointGroups[player.score] ? pointGroups[player.score].push(player) : pointGroups[player.score] = [player] } console.log('pointGroups:', pointGroups) const pairs = []; let i = pointGroups.length-1 for(i; i >= 0; i--) { const currentGroup = pointGroups[i] if (currentGroup.length % 2 === 1) { const nextGroup = pointGroups[i-1] if ( nextGroup ) { const tmpPlayer = nextGroup.splice(Math.floor(Math.random() * nextGroup.length), 1) currentGroup.push(tmpPlayer[0]) } else { currentGroup.push(playerBye) } } console.log(i+' Group:', currentGroup) for (let i = 0; i < currentGroup.length; i++) { const playerOne = getRandomByGroup(currentGroup) const playerTwo = getRandomByGroup(currentGroup) pairs.push([playerOne, playerTwo]) } } console.log('Pairs:', pairs)
Editor is loading...