day 7
Signed-off-by: Jack Bond-Preston <jackbondpreston@outlook.com>
This commit is contained in:
parent
8d22f83bf5
commit
f42d50a479
38
7/7a.cpp
Normal file
38
7/7a.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
|
||||
int main() {
|
||||
std::ifstream infile("input.txt");
|
||||
|
||||
std::vector<int> positions {};
|
||||
|
||||
int curr = 0;
|
||||
char comma;
|
||||
while (infile >> curr) {
|
||||
positions.push_back(curr);
|
||||
infile >> comma;
|
||||
}
|
||||
|
||||
int lowest = *std::min_element(std::begin(positions), std::end(positions));
|
||||
int highest = *std::max_element(std::begin(positions), std::end(positions));
|
||||
|
||||
int lowest_cost = INT_MAX;
|
||||
int best_position = 0;
|
||||
|
||||
for (int i = lowest; i < highest; i++) {
|
||||
int fuel_cost = 0;
|
||||
for (const auto &p : positions) {
|
||||
fuel_cost += std::abs(p - i);
|
||||
}
|
||||
|
||||
if (fuel_cost < lowest_cost) {
|
||||
lowest_cost = fuel_cost;
|
||||
best_position = i;
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << lowest_cost << std::endl;
|
||||
}
|
41
7/7b.cpp
Normal file
41
7/7b.cpp
Normal file
@ -0,0 +1,41 @@
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
|
||||
int main() {
|
||||
std::ifstream infile("input.txt");
|
||||
|
||||
std::vector<int> positions {};
|
||||
|
||||
int curr = 0;
|
||||
char comma;
|
||||
while (infile >> curr) {
|
||||
positions.push_back(curr);
|
||||
infile >> comma;
|
||||
}
|
||||
|
||||
int lowest = *std::min_element(std::begin(positions), std::end(positions));
|
||||
int highest = *std::max_element(std::begin(positions), std::end(positions));
|
||||
|
||||
int lowest_cost = INT_MAX;
|
||||
int best_position = 0;
|
||||
|
||||
for (int i = lowest; i < highest; i++) {
|
||||
int fuel_cost = 0;
|
||||
for (const auto &p : positions) {
|
||||
int next_cost = 1;
|
||||
for (int j = 0; j < std::abs(p - i); j++, next_cost++) {
|
||||
fuel_cost += next_cost;
|
||||
}
|
||||
}
|
||||
|
||||
if (fuel_cost < lowest_cost) {
|
||||
lowest_cost = fuel_cost;
|
||||
best_position = i;
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << lowest_cost << std::endl;
|
||||
}
|
Loading…
Reference in New Issue
Block a user