Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. int chr2idx(char c) {
  5.     return c - 'a';
  6. }
  7.  
  8. struct Set;
  9. Set empty_set();
  10. Set singleton_set(char);
  11. Set set_from_str(const char*);
  12. bool is_in_set(char, Set);
  13. Set union_set(Set, Set);
  14. Set intersection_set(Set, Set);
  15. Set diff_set(Set, Set);
  16. std::string set_to_string(Set);
  17.  
  18. struct Set {
  19.     long data;
  20.     Set(long d): data(d) {}
  21. };
  22.  
  23. Set empty_set() { return Set(0); }
  24.  
  25. Set singleton_set(char c) {
  26.     return Set(1 << chr2idx(c));
  27. }
  28.  
  29. Set set_from_str(const char* elems) {
  30.     Set s = empty_set();
  31.     while (*elems) s = union_set(s, singleton_set(*elems++));
  32.     return s;
  33. }
  34.  
  35. bool is_in_set(char c, Set s) {
  36.     int i = chr2idx(c);
  37.     return s.data & (1 << i);
  38. }
  39.  
  40. Set union_set(Set a, Set b) { return Set(a.data | b.data); }
  41.  
  42. Set intersection_set(Set a, Set b) { return Set(a.data & b.data); }
  43.  
  44. Set diff_set(Set a, Set b) { return Set(a.data - intersection_set(a, b).data); }
  45.  
  46. std::string set_to_string(Set s) {
  47.     std::string r;
  48.     for (char i = 'a'; i <= 'z'; ++i) {
  49.         if (is_in_set(i, s)) r.push_back(i);
  50.     }
  51.     return r;
  52. }
  53.  
  54. std::string parse(std::string s) {
  55.     std::string v;
  56.     v.reserve(s.size());
  57.     for (size_t i = 0; i < s.size(); ++i) {
  58.         if ('a' <= s[i] && s[i] <= 'z') v.push_back(s[i]);
  59.     }
  60.     return v;
  61. }
  62.  
  63. std::ostream& operator << (std::ostream& os, Set s) {
  64.     os << set_to_string(s);
  65.     return os;
  66. }
  67.  
  68. int _tmain(int argc, _TCHAR* argv[])
  69. {
  70.     std::cout << "Set1 = ";
  71.     std::string s1;
  72.     std::getline(std::cin, s1);
  73.     std::cout << "Set2 = ";
  74.     std::string s2;
  75.     std::getline(std::cin, s2);
  76.     s1 = parse(s1);
  77.     s2 = parse(s2);
  78.     Set set1 = set_from_str(s1.c_str());
  79.     Set set2 = set_from_str(s2.c_str());
  80.     std::cout << "Set1 or Set2 = " << union_set(set1, set2) << std::endl
  81.               << "Set1 and Set2 = " << intersection_set(set1, set2) << std::endl
  82.               << "Set1 - Set2 = " << diff_set(set1, set2) << std::endl;
  83.     std::cin >> s1;
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement