Untitled
unknown
javascript
10 days ago
1.6 kB
3
Indexable
Never
function calculateRedistribution(players) { const colors = ['green', 'red', 'blue']; const transactions = []; colors.forEach(color => { let total = 0; players.forEach(player => { total += player[color]; }); const target = total / players.length; players.forEach(player => { player[`diff_${color}`] = player[color] - target; }); while (true) { let giver = null; let taker = null; for (let i = 0; i < players.length; i++) { if (players[i][`diff_${color}`] > 0) { giver = i; } else if (players[i][`diff_${color}`] < 0) { taker = i; } if (giver !== null && taker !== null) break; } if (giver === null || taker === null) break; const transfer = Math.min(players[giver][`diff_${color}`], -players[taker][`diff_${color}`]); transactions.push({ from: players[giver].name, to: players[taker].name, color: color, amount: transfer }); players[giver][`diff_${color}`] -= transfer; players[taker][`diff_${color}`] += transfer; } }); return transactions; } // Przykład użycia: const players = [ { name: "Adrian", green: 100, red: 50, blue: 40 }, { name: "Piotr", green: 60, red: 20, blue: 10 }, { name: "Bartek", green: 10, red: 100, blue: 100 } ]; const result = calculateRedistribution(players); console.log("Transakcje do wykonania:", result);
Leave a Comment