Prize Draw

Prize Draw


题目来源:https://www.codewars.com/kata/prize-draw/train/cpp


题目简介

To participate in a prize draw each one gives his/her firstname.

Each letter of a firstname has a value which is its rank in the English alphabet. A and a have rank 1, B and b rank 2 and so on.

The length of the firstname is added to the sum of these ranks hence a number n. An array of random weights is linked to the firstnames and each n is multiplied by its corresponding weight to get what they call a winning number.

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

PAUL -> n = 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.

Task:

parameters: st a string of firstnames, we an array of weights, n a rank

return: the firstname of the participant whose rank is n (ranks are numbered from 1)

Example:

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

The function should return: PauL

Note:

If st is empty return "No participants".

If n is greater than the number of participants then return "Not enough participants".

题目简单介绍

给你一串带着名字的字符串,名字的比重=(名字长度+每个字母对应的值)*每个人的比重值

然后按照各自比重的降序以及名字的升序来排序之后,问第n人是谁


题目思路

1.解析字符串获取名字
2.计算名字所占比重
3.按照各自比重的降序以及名字的升序来排序

代码如下

#include <regex>
bool cmp(std::pair<int, std::string> a, std::pair<int, std::string> b)
{
    if (a.first != b.first)
        return a.first > b.first;
    return a.second < b.second; 
}

class Rank
{
public:
    static std::string nthRank(const std::string &st, std::vector<int> &we, int n)
    {
        if (st.empty())
            return "No participants";
        if (we.size() < n)
            return  "Not enough participants";
        std::vector<std::string> svec;
        std::regex re(",");
        std::sregex_token_iterator p(st.begin(), st.end(), re, -1);
        std::sregex_token_iterator end;
        while (p != end)        
            svec.push_back(*p++);
        std::vector<std::pair<int, std::string>> vmap;
        for(int i=0;i<svec.size();++i)
        {
            int sum = svec[i].size();
            for (int j = 0;j<svec[i].size();++j)
            {
                sum += tolower(svec[i][j]) - 'a' + 1;
            }           
            vmap.push_back(std::pair<int, std::string>(sum*we[i], svec[i] ));
        }
        sort(vmap.begin(), vmap.end(),cmp);
        return vmap[n-1].second;
    }
};

分析

就题目而言,不算太难,主要考察了对字符串分解以及排序
就代码而言,思路还是挺清晰的

  • 对正则不是很清楚的话,分解字符串可能就会用麻烦的办法
  • 在排序这里我用的是pair,个人觉得用pair的话,容易理解.当然还可以有其他的办法来实现

猜你喜欢

转载自blog.csdn.net/qq_31359295/article/details/53416157