algorithm
unknown
javascript
a year ago
2.7 kB
5
Indexable
Never
function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)) ;[array[i], array[j]] = [array[j], array[i]] } } function areSameClub(team1, team2) { return team1.club === team2.club } function hasThreeTeamsFromSameProvince(group, province) { const provinceCount = group.filter(team => team.province === province).length return provinceCount >= 3 } function isGroupFull(group) { return group.length >= 4 } // Main algorithm function distributeTeams(seedTeams, otherTeams) { const groups = { A: [], B: [], C: [], D: [] } // Shuffle seedTeams shuffleArray(seedTeams) // Assign seed teams to groups seedTeams.forEach((seedTeam, index) => { const group = Object.keys(groups)[index] groups[group].push(seedTeam) }) // Shuffle otherTeams shuffleArray(otherTeams) // As long as otherTeams is not empty, push the team to each group based on the conditions while (otherTeams.length > 0) { // Get the current last team from otherTeams and remove it from otherTeams const currentTeam = otherTeams.pop() // Find a group that satisfies 3 conditions, if all satisfied, push currentTeam to that group for (const group in groups) { const province = currentTeam.province if ( groups[group].every(team => !areSameClub(currentTeam, team)) && !hasThreeTeamsFromSameProvince(groups[group], province) && !isGroupFull(groups[group]) ) { groups[group].push(currentTeam) break } } } return groups } // ----------- Example --------------- const seedTeams = [ { name: 'Stechco1', province: 'Quebec', club: 'Stechco' }, { name: 'VietUnitedFC', province: 'BC', club: 'VietUnitedFC' }, { name: 'CICC', province: 'Ontario', club: 'CICC' }, { name: 'CalgaryVFC', province: 'Alberta', club: 'CalgaryVFC' } ] const otherTeams = [ { name: 'CTC', province: 'Ontario', club: 'CTC' }, { name: 'FCKingston', province: 'Ontario', club: 'FCKingston' }, { name: 'KWFC', province: 'Ontario', club: 'KWFC' }, { name: 'BFC', province: 'Ontario', club: 'BFC' }, { name: 'YGOfVN', province: 'Ontario', club: 'YGOfVN' }, { name: 'FCAE', province: 'Ontario', club: 'FCAE' }, { name: 'LankFC', province: 'Ontario', club: 'LankFC' }, { name: 'SFC', province: 'Quebec', club: 'SFC' }, { name: 'VMU', province: 'Quebec', club: 'VMU' }, { name: 'Stechco2', province: 'Quebec', club: 'Stechco' }, { name: 'FC3Mien', province: 'Quebec', club: 'FC3Mien' }, { name: 'RBJunior', province: 'Quebec', club: 'RBJunior' } ] const result = distributeTeams(seedTeams, otherTeams) console.log(result)