我用 Javascript 創建了一個隨機團隊生成器,它可以生成兩個隨機的團隊,每個團隊有五名球員。這是它的外觀:
我創建了一個函式來確定每個等級的值:
function getRankValue(rank) {
let rankValue;
switch(rank) {
case "platinum1" : rankValue = 2100;
break;
case "platinum2" : rankValue = 2000;
break;
case "platinum3" : rankValue = 1900;
break;
case "platinum4" : rankValue = 1800;
break;
case "gold1" : rankValue = 1650;
break;
case "gold2" : rankValue = 1550;
break;
case "gold3" : rankValue = 1450;
break;
case "gold4" : rankValue = 1350;
break;
case "silver1" : rankValue = 1200;
break;
case "silver2" : rankValue = 1100;
break;
case "silver3" : rankValue = 1000;
break;
case "silver4" : rankValue = 900;
break;
case "bronze1" : rankValue = 750;
break;
case "bronze2" : rankValue = 650;
break;
case "bronze3" : rankValue = 550;
break;
case "bronze4" : rankValue = 450;
break;
case "iron1" : rankValue = 300;
break;
case "iron2" : rankValue = 200;
break;
case "iron3" : rankValue = 100;
break;
case "iron4" : rankValue = 0;
break;
}
return rankValue;
我想讓生成器根據玩家排名值創建團隊,以創建平衡的總團隊價值。例如 :
4x Silver4(每個價值 900)和 1x 青銅 4(價值 450),總價值為 4050 對比:
3x Silver1(每個價值 1200)和 2x iron2(每個價值 200),總價值為 4000。我想讓它有一些 - 200 價值的空間,否則會太復雜。
演算法應該是什么樣子的?
uj5u.com熱心網友回復:
這是基于生成所有組合的解決方案。請注意,平衡數磁區和雙向磁區有許多實用的解決方案。此處介紹的解決方案使用了對所有 5 名玩家組合的蠻力評估。
使用Python 組合函式 作為參考,combinations下面的迭代器函式的 Javascript 版本從提供的 10 名球員排名串列中生成 5 名球員的組合。整體解決方案是蠻力,因為它迭代 5 名球員的所有組合,并根據團隊價值的最小差異回傳最佳球員組合。
function *combinations( combo, list, k ) {
if ( k == 0 ) {
yield combo;
} else {
for ( let i = 0; i < list.length; i ) {
yield *combinations( [...combo, list[ i ] ], list.slice( i 1 ), k - 1 );
}
}
}
let players = [ 1200, 1200, 1200, 900, 900, 900, 900, 450, 200, 200 ];
let playersTotal = players.reduce( ( sum, player ) => sum = player, 0 );
let team1 = combinations( [], players, 5 );
let nextCombo;
let minCombo, minDiff = Number.MAX_SAFE_INTEGER;
do {
nextCombo = team1.next().value;
if ( nextCombo == null ) break;
let team1Sum = nextCombo.reduce( ( sum, player ) => sum = player, 0 );
let diff = Math.abs( ( playersTotal - team1Sum ) - team1Sum );
if ( diff < minDiff ) {
minCombo = nextCombo;
minDiff = diff;
}
if ( diff <= 200 ) {
console.log( `Team: ${nextCombo.join( ',' )}, Total: ${team1Sum}, Diff: ${diff}` );
}
} while ( true );
console.log( `Best matchup is Team 1 of ${minCombo} with diff of ${minDiff}` );
請注意,如果對最近的結果感到滿意,則使用迭代器函式來生成組合的優點是可以終止對進一步組合的請求。這還有一個好處,如果搜索較大的團隊,計算所有組合是不切實際的,可以在回圈中添加一個計時器,以獲取下一個團隊組合,并在計時器結束后使用最佳結果,以便限制搜索時間。在這種情況下,明智的做法是在呼叫之前隨機打亂玩家串列,combinations這樣生成的組合就不會全部都擠滿了最好的玩家,從而有更好的機會獲得平衡的團隊配對......
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380286.html
標籤:javascript 算法 数学
上一篇:獲取比為質數的數的除數
