解决此排序问题的最佳方法是什么?

问题描述 投票:0回答:1

为了参加抽奖,每个人都给他/她的名字。

每个名字的字母的值是它在英语字母表中的排名。 A和a的等级为1,B和b的等级为2,依此类推。

名字的长度被加到这些等级的总和上,从而得到一个数字。

随机权重的数组与名字相关联,每个som乘以其相应的权重以获得他们所谓的中奖号码。

示例:

names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]

PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54
The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108.
Now one can sort the firstnames in decreasing order of the winning numbers. When two people have the same winning number sort them alphabetically by their firstnames.

任务:参数:st个名字字符串,我们是一个权重数组,n个等级

返回:等级为n(等级从1开始编号)的参与者的名字]

现在可以按中奖号码的降序对名字进行排序。当两个人的中奖号码相同时,请按名字的字母顺序对其进行排序。

这是我的解决方案,但是不能解决名称的数字值相同的情况(我使用第一个值)。

function charToNumber (s, i) {
    return parseInt(s.charAt(i), 36) - 9;
}

function sumChars (s, weight) {
    var i = s.length, r = 0;
    while (--i >= 0) r += charToNumber(s, i);
    return r + s.length;
}


function rank(st, we, n) {
    let result, arr
    const hashTable = {};
    let resultsArr = [];
    arr = st.split(',')
    if (st.length === 0) {
      return "No participants";
    } else if (n > arr.length) {
      return "Not enough participants";
    }

    arr.forEach((name, i) => {
        const total = sumChars(name) * we[i];
        hashTable[name] = total;
        nameMap.set(name, total);
        resultsArr.push(total);
    });

    resultsArr.sort((a, b) => a - b).reverse();
    const correctSum = resultsArr[n-1];


    for (const prop in hashTable) {
        if (hashTable[prop] === correctSum) {
          result = prop;
          break;
        }
     }
    return result;
}

//rank('Grace,Jacob,Jayden,Daniel,Lily,Samantha,Aubrey,David,Liam,Willaim,Addison,Robert,Alexander,Avery,Isabella,Mia,Noah,James,Olivai,Emily,Ella,Sophia,Natalie,Benjamin,Lyli,Madison', [2,4,1,1,3,6,6,4,4,5,4,6,3,6,6,6,6,6,5,6,5,1,4,1,5,5], 7);
// should return 'Isabella'
//rank('Emily,Benjamin,Ava,Joshua,Isabella,Michael,Matthew,Olivai,William,Willaim,David,Lyli', [3,3,3,6,6,4,6,6,3,3,6,4], 6);
// should return 'Willaim', not 'William'
javascript string algorithm sorting
1个回答
0
投票
var names = ["COLIN","AMANDBA","AMANDAB","CAROL","PauL","JOSEPH"]; var weights = [1, 4, 4, 5, 2, 1]; function compute_score(name, weight) { // XXX: code for computing the actual score goes her return weight; } function winner(names, weights) { var scores = {}; for (var ii=0; ii < names.length; ii++) { scores[names[ii]] = compute_score(name, weight); } return names.sort( function (a,b) { if (scores[a] > scores[b]) return -1; if (scores[a] < scores[b]) return +1; if (a.toLowerCase() < b.toLowerCase()) return -1; if (a.toLowerCase() > b.toLowerCase()) return +1; return 0; // equal } )[0]; } console.log(winner(names, weights));

CAROL
注意,我不会对错误进行检查(空列表等),请小心。
© www.soinside.com 2019 - 2024. All rights reserved.