Advertisement
Guest User

Untitled

a guest
Dec 6th, 2021
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1.  
  2. #include <bitset>
  3. #include <vector>
  4. static void Day3A_()
  5. {
  6.     std::ifstream infile("3.txt");
  7.     std::bitset<12> currBitset;
  8.     std::vector<int> binaryCount(12);
  9.     while (infile >> currBitset)
  10.     {
  11.         for (unsigned i = 0; i < currBitset.size(); ++i)
  12.         {
  13.             currBitset.test(i) ? binaryCount[i]++ : binaryCount[i]--;
  14.         }
  15.     }
  16.  
  17.     std::bitset<12> gamma;
  18.     for (unsigned i = 0; i < binaryCount.size(); ++i)
  19.     {
  20.         gamma.set(i, binaryCount[i] GT 0);
  21.     }
  22.     auto epsilon = ~gamma;
  23.  
  24.     std::cout << "3A:" << gamma.to_ulong() * epsilon.to_ulong() << "\n";
  25. }
  26.  
  27. using Bitset = std::bitset<12>;
  28. bool MajoritySet_(int index, const std::vector<Bitset>& list)
  29. {
  30.     int count = 0;
  31.     for (const auto& currBitset : list)
  32.     {
  33.         currBitset.test(index) ? count++ : count--;
  34.     }
  35.     return count GE 0;
  36. }
  37. #include <functional>
  38. using ComparisonFunc = std::function<bool(bool, bool)>;
  39. int FilteredValue_(std::vector<Bitset> list, //copied list since it is modified. HOWEVER, could use std::partition instead of erase_if
  40.     const ComparisonFunc& func)
  41. {
  42.     for (unsigned index = 11; list.size() GT 1 AND index GE 0; --index)
  43.     {
  44.         bool isSet = MajoritySet_(index, list);
  45.         std::erase_if(list, [&](const Bitset& bit) {return func(bit.test(index), isSet); });
  46.     }
  47.     _ASSERT(list.size() EQ 1);
  48.     return list.front().to_ulong();
  49. }
  50.  
  51. static void Day3B_()
  52. {
  53.     /*
  54.     In string form:
  55.     100000101101
  56.     ^          ^
  57.     11th       0th exponent
  58.  
  59.     In bitset,
  60.     101101000001
  61.     ^          ^
  62.     0th        11th exponent
  63.     */
  64.     std::vector<Bitset> list;
  65.     std::ifstream infile("3.txt");
  66.     Bitset currBitset;
  67.     while (infile >> currBitset)
  68.     {
  69.         list.push_back(currBitset);
  70.     }
  71.     auto first = FilteredValue_(list, [](const bool b1, const bool b2) {return b1 NE b2; }); //Erase things NOT matching majority
  72.     auto second = FilteredValue_(list, [](const bool b1, const bool b2) {return b1 EQ b2; }); //Erase things matching majority.
  73.     std::cout << "3B:" << first * second << "\n";
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement