You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

抽奖排名算法问题求助:相同获胜数的姓名排序逻辑修正

Fixing the Tiebreaker Logic for Your Lottery Ranking Function

Got it, let's get this sorted out! The core issue with your current implementation is that it doesn't handle ties in winning numbers correctly—when multiple names have the same score, you're just picking the first one you encounter in the hash table, which doesn't follow the "alphabetical ascending order" rule. Plus, relying on a hash table and separate array of scores makes it hard to keep names tied to their scores properly during sorting.

What Was Wrong with the Original Code

  • You stored scores in a hash table, but object key order isn't guaranteed in JavaScript, so you can't rely on it to sort names alphabetically when scores are equal.
  • When you found the score matching the nth rank, you just grabbed the first name with that score, which ignores the tiebreaker rule.
  • There was an unused nameMap variable that was causing a reference error (it wasn't defined anywhere).

Corrected Implementation

Here's the revised code that properly handles both the score sorting and tiebreaker:

function charToNumber(s, i) {
    // Convert character to its alphabetical position (A/a=1, B/b=2, etc.)
    return parseInt(s.charAt(i).toLowerCase(), 36) - 9;
}

function calculateSom(s) {
    let sum = 0;
    for (let i = 0; i < s.length; i++) {
        sum += charToNumber(s, i);
    }
    // SOM = name length + sum of character positions
    return sum + s.length;
}

function rank(st, we, n) {
    const participants = st.split(',');
    
    // Handle edge cases first
    if (participants.length === 0) {
        return "No participants";
    }
    if (n > participants.length) {
        return "Not enough participants";
    }

    // Create an array of objects linking each name to its final winning score
    const rankedParticipants = participants.map((name, index) => {
        const som = calculateSom(name);
        const winningScore = som * we[index];
        return { name, score: winningScore };
    });

    // Sort the array: first by score descending, then by name ascending (case-insensitive)
    rankedParticipants.sort((a, b) => {
        // First compare scores
        if (b.score !== a.score) {
            return b.score - a.score;
        }
        // If scores are equal, sort names alphabetically (ignore case)
        return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
    });

    // Return the nth participant (since ranks start at 1, use index n-1)
    return rankedParticipants[n - 1].name;
}

// Test case 1: Should return 'Isabella'
console.log(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));

// Test case 2: Should return 'Willaim'
console.log(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));

Key Improvements

  1. Linked Score-Name Objects: Instead of separating names and scores into different structures, we create an array of objects that keeps each name paired with its winning score. This makes sorting straightforward.
  2. Proper Sorting Logic: The sort function first compares scores in descending order. If scores are equal, it uses localeCompare with sensitivity: 'base' to sort names alphabetically while ignoring case differences (which aligns with the problem's letter position calculation that treats uppercase and lowercase letters the same).
  3. Cleaner Edge Case Handling: We split the input string first and check edge cases immediately, making the code easier to read.
  4. Renamed Functions: sumChars was renamed to calculateSom for clarity, since it computes the SOM value as defined in the problem.

This code will correctly handle both test cases and any other scenarios where multiple participants have the same winning number.

内容的提问来源于stack exchange,提问作者eagercoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:02:53