Lexicographically largest string from allowed swaps












1














Problem: Given a string str and array of pairs that indicates which indices in the string can be swapped, return the lexicographically largest string that results from doing the allowed swaps. You can swap indices any number of times.



Example



For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be
swapLexOrder(str, pairs) = "dbca".



By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca".



My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.



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

std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs)
{
if(pairs.size() == 0) return str;
std::vector<std::set<int>> pairpool; //pairpool : contains sets of interchangeable indices
std::vector<std::vector<std::string>> stringpool; //stringpool : contains vectors of interchangeable characters

//creates pairpool structure
for(std::size_t i = 0; i < pairs.size(); i++)
{
bool alrExists = false;
std::set<int> newSet;
for(auto& p : pairpool)
{
for(auto ele : p)
{
if((pairs[i][0] == ele) || (pairs[i][1] == ele))
{
if(!alrExists)
{
alrExists = true;
p.insert(pairs[i][0]);
p.insert(pairs[i][1]);
newSet = p;
}
else
{
if(p == newSet) break;
p.insert(newSet.begin(), newSet.end());
pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end());
break; // needed this break statement really badly
}
}
}
}
if(!alrExists)
{
newSet.insert(pairs[i][0]);
newSet.insert(pairs[i][1]);
pairpool.push_back(newSet);
}
}

//creates sorted stringpool structure
for(auto p : pairpool)
{
std::vector<std::string> newset;
for(auto ele : p)
{
newset.push_back(str.substr(ele - 1, 1));
}
std::sort(newset.begin(), newset.end());
stringpool.push_back(newset);
}

//uses stringpool and pairpool to modify string only one time through
int counter = 0;
for(auto p : pairpool)
{
for(auto ele : p)
{
str.replace(ele - 1, 1, stringpool[counter].back());
stringpool[counter].pop_back();
}
counter++;
}

return str;
}

int main()
{
std::cout << swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) << "n";
std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv";
std::vector<std::vector<int>> PAIR =
{
{13, 23},
{13, 28},
{15, 20},
{24, 29},
{6, 7},
{3, 4},
{21, 30},
{2, 13},
{12, 15},
{19, 23},
{10, 19},
{13, 14},
{6, 16},
{17, 25},
{6, 21},
{17, 26},
{5, 6},
{12, 24}
};
std::cout << swapLexOrder(STR, PAIR) << "n";
return 0;
}









share|improve this question



























    1














    Problem: Given a string str and array of pairs that indicates which indices in the string can be swapped, return the lexicographically largest string that results from doing the allowed swaps. You can swap indices any number of times.



    Example



    For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be
    swapLexOrder(str, pairs) = "dbca".



    By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca".



    My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.



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

    std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs)
    {
    if(pairs.size() == 0) return str;
    std::vector<std::set<int>> pairpool; //pairpool : contains sets of interchangeable indices
    std::vector<std::vector<std::string>> stringpool; //stringpool : contains vectors of interchangeable characters

    //creates pairpool structure
    for(std::size_t i = 0; i < pairs.size(); i++)
    {
    bool alrExists = false;
    std::set<int> newSet;
    for(auto& p : pairpool)
    {
    for(auto ele : p)
    {
    if((pairs[i][0] == ele) || (pairs[i][1] == ele))
    {
    if(!alrExists)
    {
    alrExists = true;
    p.insert(pairs[i][0]);
    p.insert(pairs[i][1]);
    newSet = p;
    }
    else
    {
    if(p == newSet) break;
    p.insert(newSet.begin(), newSet.end());
    pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end());
    break; // needed this break statement really badly
    }
    }
    }
    }
    if(!alrExists)
    {
    newSet.insert(pairs[i][0]);
    newSet.insert(pairs[i][1]);
    pairpool.push_back(newSet);
    }
    }

    //creates sorted stringpool structure
    for(auto p : pairpool)
    {
    std::vector<std::string> newset;
    for(auto ele : p)
    {
    newset.push_back(str.substr(ele - 1, 1));
    }
    std::sort(newset.begin(), newset.end());
    stringpool.push_back(newset);
    }

    //uses stringpool and pairpool to modify string only one time through
    int counter = 0;
    for(auto p : pairpool)
    {
    for(auto ele : p)
    {
    str.replace(ele - 1, 1, stringpool[counter].back());
    stringpool[counter].pop_back();
    }
    counter++;
    }

    return str;
    }

    int main()
    {
    std::cout << swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) << "n";
    std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv";
    std::vector<std::vector<int>> PAIR =
    {
    {13, 23},
    {13, 28},
    {15, 20},
    {24, 29},
    {6, 7},
    {3, 4},
    {21, 30},
    {2, 13},
    {12, 15},
    {19, 23},
    {10, 19},
    {13, 14},
    {6, 16},
    {17, 25},
    {6, 21},
    {17, 26},
    {5, 6},
    {12, 24}
    };
    std::cout << swapLexOrder(STR, PAIR) << "n";
    return 0;
    }









    share|improve this question

























      1












      1








      1







      Problem: Given a string str and array of pairs that indicates which indices in the string can be swapped, return the lexicographically largest string that results from doing the allowed swaps. You can swap indices any number of times.



      Example



      For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be
      swapLexOrder(str, pairs) = "dbca".



      By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca".



      My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.



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

      std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs)
      {
      if(pairs.size() == 0) return str;
      std::vector<std::set<int>> pairpool; //pairpool : contains sets of interchangeable indices
      std::vector<std::vector<std::string>> stringpool; //stringpool : contains vectors of interchangeable characters

      //creates pairpool structure
      for(std::size_t i = 0; i < pairs.size(); i++)
      {
      bool alrExists = false;
      std::set<int> newSet;
      for(auto& p : pairpool)
      {
      for(auto ele : p)
      {
      if((pairs[i][0] == ele) || (pairs[i][1] == ele))
      {
      if(!alrExists)
      {
      alrExists = true;
      p.insert(pairs[i][0]);
      p.insert(pairs[i][1]);
      newSet = p;
      }
      else
      {
      if(p == newSet) break;
      p.insert(newSet.begin(), newSet.end());
      pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end());
      break; // needed this break statement really badly
      }
      }
      }
      }
      if(!alrExists)
      {
      newSet.insert(pairs[i][0]);
      newSet.insert(pairs[i][1]);
      pairpool.push_back(newSet);
      }
      }

      //creates sorted stringpool structure
      for(auto p : pairpool)
      {
      std::vector<std::string> newset;
      for(auto ele : p)
      {
      newset.push_back(str.substr(ele - 1, 1));
      }
      std::sort(newset.begin(), newset.end());
      stringpool.push_back(newset);
      }

      //uses stringpool and pairpool to modify string only one time through
      int counter = 0;
      for(auto p : pairpool)
      {
      for(auto ele : p)
      {
      str.replace(ele - 1, 1, stringpool[counter].back());
      stringpool[counter].pop_back();
      }
      counter++;
      }

      return str;
      }

      int main()
      {
      std::cout << swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) << "n";
      std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv";
      std::vector<std::vector<int>> PAIR =
      {
      {13, 23},
      {13, 28},
      {15, 20},
      {24, 29},
      {6, 7},
      {3, 4},
      {21, 30},
      {2, 13},
      {12, 15},
      {19, 23},
      {10, 19},
      {13, 14},
      {6, 16},
      {17, 25},
      {6, 21},
      {17, 26},
      {5, 6},
      {12, 24}
      };
      std::cout << swapLexOrder(STR, PAIR) << "n";
      return 0;
      }









      share|improve this question













      Problem: Given a string str and array of pairs that indicates which indices in the string can be swapped, return the lexicographically largest string that results from doing the allowed swaps. You can swap indices any number of times.



      Example



      For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be
      swapLexOrder(str, pairs) = "dbca".



      By swapping the given indices, you get the strings: "cbda", "cbad", "dbac", "dbca". The lexicographically largest string in this list is "dbca".



      My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.



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

      std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs)
      {
      if(pairs.size() == 0) return str;
      std::vector<std::set<int>> pairpool; //pairpool : contains sets of interchangeable indices
      std::vector<std::vector<std::string>> stringpool; //stringpool : contains vectors of interchangeable characters

      //creates pairpool structure
      for(std::size_t i = 0; i < pairs.size(); i++)
      {
      bool alrExists = false;
      std::set<int> newSet;
      for(auto& p : pairpool)
      {
      for(auto ele : p)
      {
      if((pairs[i][0] == ele) || (pairs[i][1] == ele))
      {
      if(!alrExists)
      {
      alrExists = true;
      p.insert(pairs[i][0]);
      p.insert(pairs[i][1]);
      newSet = p;
      }
      else
      {
      if(p == newSet) break;
      p.insert(newSet.begin(), newSet.end());
      pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end());
      break; // needed this break statement really badly
      }
      }
      }
      }
      if(!alrExists)
      {
      newSet.insert(pairs[i][0]);
      newSet.insert(pairs[i][1]);
      pairpool.push_back(newSet);
      }
      }

      //creates sorted stringpool structure
      for(auto p : pairpool)
      {
      std::vector<std::string> newset;
      for(auto ele : p)
      {
      newset.push_back(str.substr(ele - 1, 1));
      }
      std::sort(newset.begin(), newset.end());
      stringpool.push_back(newset);
      }

      //uses stringpool and pairpool to modify string only one time through
      int counter = 0;
      for(auto p : pairpool)
      {
      for(auto ele : p)
      {
      str.replace(ele - 1, 1, stringpool[counter].back());
      stringpool[counter].pop_back();
      }
      counter++;
      }

      return str;
      }

      int main()
      {
      std::cout << swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) << "n";
      std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv";
      std::vector<std::vector<int>> PAIR =
      {
      {13, 23},
      {13, 28},
      {15, 20},
      {24, 29},
      {6, 7},
      {3, 4},
      {21, 30},
      {2, 13},
      {12, 15},
      {19, 23},
      {10, 19},
      {13, 14},
      {6, 16},
      {17, 25},
      {6, 21},
      {17, 26},
      {5, 6},
      {12, 24}
      };
      std::cout << swapLexOrder(STR, PAIR) << "n";
      return 0;
      }






      c++ algorithm sorting






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 34 mins ago









      Bo Work

      695




      695



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210321%2flexicographically-largest-string-from-allowed-swaps%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210321%2flexicographically-largest-string-from-allowed-swaps%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'