Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- int chr2idx(char c) {
- return c - 'a';
- }
- struct Set;
- Set empty_set();
- Set singleton_set(char);
- Set set_from_str(const char*);
- bool is_in_set(char, Set);
- Set union_set(Set, Set);
- Set intersection_set(Set, Set);
- Set diff_set(Set, Set);
- std::string set_to_string(Set);
- struct Set {
- long data;
- Set(long d): data(d) {}
- };
- Set empty_set() { return Set(0); }
- Set singleton_set(char c) {
- return Set(1 << chr2idx(c));
- }
- Set set_from_str(const char* elems) {
- Set s = empty_set();
- while (*elems) s = union_set(s, singleton_set(*elems++));
- return s;
- }
- bool is_in_set(char c, Set s) {
- int i = chr2idx(c);
- return s.data & (1 << i);
- }
- Set union_set(Set a, Set b) { return Set(a.data | b.data); }
- Set intersection_set(Set a, Set b) { return Set(a.data & b.data); }
- Set diff_set(Set a, Set b) { return Set(a.data - intersection_set(a, b).data); }
- std::string set_to_string(Set s) {
- std::string r;
- for (char i = 'a'; i <= 'z'; ++i) {
- if (is_in_set(i, s)) r.push_back(i);
- }
- return r;
- }
- std::string parse(std::string s) {
- std::string v;
- v.reserve(s.size());
- for (size_t i = 0; i < s.size(); ++i) {
- if ('a' <= s[i] && s[i] <= 'z') v.push_back(s[i]);
- }
- return v;
- }
- std::ostream& operator << (std::ostream& os, Set s) {
- os << set_to_string(s);
- return os;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- std::cout << "Set1 = ";
- std::string s1;
- std::getline(std::cin, s1);
- std::cout << "Set2 = ";
- std::string s2;
- std::getline(std::cin, s2);
- s1 = parse(s1);
- s2 = parse(s2);
- Set set1 = set_from_str(s1.c_str());
- Set set2 = set_from_str(s2.c_str());
- std::cout << "Set1 or Set2 = " << union_set(set1, set2) << std::endl
- << "Set1 and Set2 = " << intersection_set(set1, set2) << std::endl
- << "Set1 - Set2 = " << diff_set(set1, set2) << std::endl;
- std::cin >> s1;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement