Skip to content

Instantly share code, notes, and snippets.

@system123
Last active December 8, 2021 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save system123/bdaa37c8b3b58848e969377f9e320c61 to your computer and use it in GitHub Desktop.
Save system123/bdaa37c8b3b58848e969377f9e320c61 to your computer and use it in GitHub Desktop.
AoC2021 Problem 7
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
template <typename T>
vector<T> line2vec(string line, char sep = ',')
{
vector<T> arr;
stringstream ss(line);
for (T i; ss >> i;)
{
arr.push_back(i);
while (ss.peek() == sep)
ss.ignore();
}
return arr;
}
int main(int argc, char *argv[])
{
std::ifstream fin;
string line;
vector<int> crabs;
long totalEnergy = 0;
std::function<int(int)> arithSum = [=](int dist) -> float
{ return dist * (dist + 1) / 2; };
// Read the input and populate the population
fin.open(argv[1], std::ios_base::in);
getline(fin, line);
crabs = line2vec<int>(line, ',');
// Find the median value
sort(crabs.begin(), crabs.end());
int n = crabs.size();
double moveTo = (double)(crabs[(n - 1) / 2] + crabs[n / 2]) / 2.0;
// Part 1
for (int c : crabs)
{
totalEnergy += abs(moveTo - c);
}
cout << "Total Energy: " << totalEnergy << endl;
// Part 2
moveTo = std::accumulate(crabs.begin(), crabs.end(), decltype(crabs)::value_type(0));
moveTo /= double(crabs.size());
int moveToDisc_ceil = static_cast<int>(ceil(moveTo));
int moveToDisc_floor = static_cast<int>(floor(moveTo));
int totalEnergy_up = 0;
int totalEnergy_down = 0;
for (int c : crabs)
{
totalEnergy_up += arithSum(abs(moveToDisc_ceil - c));
totalEnergy_down += arithSum(abs(moveToDisc_floor - c));
}
totalEnergy = min(totalEnergy_up, totalEnergy_down);
cout
<< "Part2: " << totalEnergy << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment