advent_of_code_2021/25/main.cpp
2022-12-04 10:46:26 +01:00

147 lines
4.2 KiB
C++

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
enum Cucumber {
NONE,
RIGHT,
DOWN,
};
std::vector<std::vector<Cucumber>> getMap(const std::string &file_name) {
std::ifstream file(file_name);
std::vector<std::vector<Cucumber>> result{};
int tmp = 0;
std::string str;
while (std::getline(file, str)) {
result.emplace_back();
for(auto &c : str) {
switch(c) {
case 'v':
result.back().push_back(DOWN);
break;
case '>':
result.back().push_back(RIGHT);
break;
default:
result.back().push_back(NONE);
break;
}
}
}
return result;
}
std::vector<std::vector<Cucumber>> createEmptyMap(size_t height, size_t width) {
std::vector<std::vector<Cucumber>> res{};
res.resize(height);
for(size_t i = 0; i < height; i++) {
res[i].resize(width);
for(size_t j = 0; j < width; j++) {
res[i][j] = NONE;
}
}
return res;
}
bool mapsAreEqual(const std::vector<std::vector<Cucumber>> &a, const std::vector<std::vector<Cucumber>> &b) {
for(size_t i = 0; i < a.size(); i++) {
for(size_t j = 0; j < a[0].size(); j++) {
if(a[i][j] != b[i][j]) {
return false;
}
}
}
return true;
}
void printMap(const std::vector<std::vector<Cucumber>> &input) {
for(size_t i = 0; i < input.size(); i++) {
for(size_t j = 0; j < input[0].size(); j++) {
char print = '.';
switch(input[i][j]) {
case DOWN:
print = 'v';
break;
case RIGHT:
print = '>';
default:
break;
}
std::cout << print;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
uint64_t part1(const std::vector<std::vector<Cucumber>> &input) {
auto cur_map = input;
auto next_map = input;
uint64_t rounds = 0;
do {
cur_map = next_map;
next_map = createEmptyMap(cur_map.size(), cur_map[0].size());
rounds++;
for(size_t i = 0; i < input.size(); i++) {
for(size_t j = 0; j < input[0].size(); j++) {
size_t next_i = i;
size_t next_j = j;
switch(cur_map[i][j]) {
case RIGHT:
next_j += 1;
if(next_j >= cur_map[0].size()) {
next_j = 0;
}
break;
case DOWN:
default:
continue;
break;
}
if(cur_map[next_i][next_j] == NONE) {
next_map[next_i][next_j] = cur_map[i][j];
} else {
next_map[i][j] = cur_map[i][j];
}
}
}
for(size_t i = 0; i < input.size(); i++) {
for(size_t j = 0; j < input[0].size(); j++) {
size_t next_i = i;
size_t next_j = j;
switch(cur_map[i][j]) {
case DOWN:
next_i += 1;
if(next_i >= cur_map.size()) {
next_i = 0;
}
break;
case RIGHT:
default:
continue;
break;
}
if(cur_map[next_i][next_j] != DOWN && next_map[next_i][next_j] == NONE) {
next_map[next_i][next_j] = cur_map[i][j];
} else {
next_map[i][j] = cur_map[i][j];
}
}
}
} while(!mapsAreEqual(cur_map, next_map));
return rounds;
}
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "You must provide input file!" << std::endl;
return 1;
}
auto map = getMap(argv[1]);
std::cout << "The see cucumbers stop moving after \033[91;1m" << part1(map)
<< "\033[0m steps." << std::endl;
return 0;
}