Tuesday, February 20, 2018

generate permutations of letters in a string

how to generate all permutations of the letters in a string? one method i like, for its intuitiveness - go to the last letter of the string and then recursively create strings by inserting previous letters in all possible positions. at each step a new list of strings will be created, with growing lengths

#include 
#include 
#include 

std::vector permute(std::string s, size_t index) {
    //std::cout << s << " " << index << std::endl;
    std::vector perms;
    if (index >= s.length()) {
        perms.push_back("");
        return perms;
    }
    
    std::string key = s.substr(index, 1);
    std::vector prev = permute(s, index + 1);
    for (size_t i = 0; i < prev.size(); ++i) {
        std::string p = prev[i];
        for (size_t j = 0; j <= p.length(); ++j) {
            std::string n = p.insert(j, key);
            perms.push_back(n);
            p = prev[i];
        }
    }
    return perms;
}

int main()
{
  std::string name = "12345";
  std::vector perms = permute(name, 0);
  for (auto& p : perms) {
    std::cout << p << std::endl;
  }
}

12345
21345
23145
23415
23451
13245
....


Saturday, February 17, 2018

Removing Characters from a String

found an interesting learning resource http://www.bogotobogo.com/ it also has a section on programming questions, not so extensive as the awesome http://geeksforgeeks.org/, but has some good problems to solve, with solutions. here is my solution to the "Removing Characters from a String" problem (http://www.bogotobogo.com/cplusplus/quiz_strings_arrays.php). it is not better, just a different approach
#include 
#include 

int main()
{
  std::string name("Ludwig Van Beethoven");
  std::string remove("aeiouAEIOU");
  int walk = 0;
  int last = 1;
  while (last < name.length() && walk < name.length()) {
      auto found = remove.find(name[walk], 0);
      if (found != std::string::npos) {
          char ch = name[walk];
          name[walk] = name[last];
          name[last] = ch;
          ++last;
      } else {
          ++walk;
      }
  }
  std::cout << "Hello, " << name.substr(0, walk+1) << "!\n";
}