Duplicate Character Question

Asked 2 years ago, Updated 2 years ago, 25 views

Issue)

['hong', 'a', 'a', 'a'], ['hong', 'a', 'b'], ['park', 'a', 'b', 'c'], ['hong', 'e', 'f', 'g'], ['park', 'a', 'a', 'b', 'b'] 

Given the following arrangement,

Alphabet that hong has (duplicated x) a,b,e,f,g => 5

Alphabet that park has (duplicated x) a.b.c => 3p

Therefore, Hong has the most alphabets.

Output) Name output of the person who has the most different alphabets, (name always precedes an array) 'hong'

You want to solve the following problems:

I tried to solve it using a map or a hash table. I don't know how to solve it, so I'm asking you a question.

Please give me a big overview of the puzzle

c++

2022-09-22 18:37

1 Answers

#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

void sort_display(std::map<std::string, std::set<std::string>> &dict)
{
    std::vector<std::pair<std::string, std::set<std::string>>> copy(dict.begin(), dict.end());

    // // sort by size() of letter set
    std::sort(copy.begin(), copy.end(), [](auto& a, auto& b) { return a.second.size() > b.second.size(); });

    // // print sorted vector
    for (auto& d : copy)
    {
        std::cout << d.first << ": ";
        for (auto e : d.second)
        {
            std::cout << e << ", ";
        }
        std::cout << std::endl;
    }
}

int main()
{
    std::vector<std::vector<std::string>> data = { { "hong","a","a","a" }, { "hong","a","b" }, { "park","a","b","c" }, { "hong","e","f","g"},{"park","a","a","b","b"} };
    std::map<std::string, std::set<std::string>> dict;
    std::string name;
    std::set<std::string> s;

    // // merge data into a map structure, by the first string of each data.
    for (auto row : data)
    {
        name = row[0];  // first element is the name
        s = std::set<std::string>(row.begin() + 1, row.end()); // other elements are converted into a set
        if (dict.find(name) == dict.end())
        {
            dict[name] = s;
        }
        else
        {
            dict[name].insert(s.begin(), s.end());
        }
    }

    sort_display(dict);

    return 0;
}


2022-09-22 18:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.