Skip to content

Instantly share code, notes, and snippets.

@johngian
Created December 5, 2021 09:58
Show Gist options
  • Save johngian/2554eaa48a8dff8d35a8a17b49389074 to your computer and use it in GitHub Desktop.
Save johngian/2554eaa48a8dff8d35a8a17b49389074 to your computer and use it in GitHub Desktop.
Advent of code 2021 - day 3 - solution
#include <iostream>
#include <algorithm>
#include <math.h>
#include <set>
#include <vector>
#include <tuple>
#include <numeric>
#include <bitset>
#include <math.h>
#include <day3.hpp>
namespace day3
{
std::string solution_part1(std::istream &std_input)
{
std::string line;
std::vector<int> counters;
int total = 0;
while (std::getline(std_input, line))
{
for (int i = 0; i < line.size(); i++)
{
int elem = line[i] - '0';
if (counters.size() < i + 1)
{
counters.push_back(0);
}
counters[i] += elem;
}
total++;
}
int gamma = 0, epsilon = 0;
for (int i = 0; i < counters.size(); i++)
{
int curr_bit = (counters[i] > (total - counters[i])) ? 1 : 0;
gamma += curr_bit * pow(2, (counters.size() - i - 1));
epsilon += (1 - curr_bit) * pow(2, (counters.size() - i - 1));
}
return std::to_string(gamma * epsilon);
}
std::tuple<int, int> report(std::vector<std::string> nums, bool order)
{
int low = 0, high = nums.size() - 1;
for (int i = 0; i < nums[0].size(); i++)
{
std::string current;
int zeros = 0;
int ones = 0;
for (int j = low; j < high + 1; j++)
{
char elem = nums[j][i];
current.push_back(elem);
zeros += (elem == '0') ? 1 : 0;
ones += (elem == '1') ? 1 : 0;
}
if (high == low)
{
break;
}
if (zeros == 0 || ones == 0)
{
continue;
}
if (zeros <= ones)
{
if (order)
{
low += zeros;
}
else
{
high = low + zeros - 1;
}
}
else
{
if (order)
{
high = low + zeros - 1;
}
else
{
low += zeros;
}
}
}
return std::make_tuple(low, high);
}
std::string solution_part2(std::istream &std_input)
{
std::string line;
std::vector<std::string> nums;
while (std::getline(std_input, line))
{
nums.push_back(line);
}
std::sort(nums.begin(), nums.end());
std::string o2_result = nums[std::get<1>(report(nums, true))];
std::string co2_result = nums[std::get<0>(report(nums, false))];
std::bitset<64> o2(o2_result);
std::bitset<64> co2(co2_result);
return std::to_string(o2.to_ulong() * co2.to_ulong());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment