it is sometimes hard to understand what they ment

This commit is contained in:
PoliEcho 2024-12-13 14:45:46 +01:00
parent 8ae76ad885
commit 598de252fe

138
day4/second.cpp Normal file
View File

@ -0,0 +1,138 @@
#include <asm-generic/errno.h>
#include <cstdlib>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <vector>
#define RANGE 1
int res;
bool AreWeInBounds(int i, int j, std::vector<std::vector<char>> &wordsearch) {
if (i < 0 || j < 0) {
return false;
}
if (i >= wordsearch.size() || j >= wordsearch[i].size()) {
return false;
}
return true;
}
int conditional_operation(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
default:
return a;
}
}
int Check(std::vector<std::vector<char>> &wordsearch, int i, int j) {
int xmases = 0;
char op_i;
char op_j;
// array to store the 4 directions
/*
0 1
a
2 3
*/
char xarray[4] = {'\0', '\0', '\0', '\0'};
for (int w = 0; w < 4; w++) {
switch (w) {
case 0:
// search up-left
op_i = '-';
op_j = '-';
if (!AreWeInBounds(i - RANGE, j - RANGE, wordsearch)) {
continue;
}
break;
case 1:
// search up-right
op_i = '-';
op_j = '+';
if (!AreWeInBounds(i - RANGE, j + RANGE, wordsearch)) {
continue;
}
break;
case 2:
// search down-left
op_i = '+';
op_j = '-';
if (!AreWeInBounds(i + RANGE, j - RANGE, wordsearch)) {
continue;
}
break;
case 3:
// search down-right
op_i = '+';
op_j = '+';
if (!AreWeInBounds(i + RANGE, j + RANGE, wordsearch)) {
continue;
}
break;
default:
std::cerr << "How did we get here?" << std::endl;
exit(255);
break;
}
if (wordsearch[i][j] == 'A') {
if (wordsearch[conditional_operation(i, 1, op_i)]
[conditional_operation(j, 1, op_j)] == 'M' ||
wordsearch[conditional_operation(i, 1, op_i)]
[conditional_operation(j, 1, op_j)] == 'S') {
xarray[w] = wordsearch[conditional_operation(i, 1, op_i)]
[conditional_operation(j, 1, op_j)];
}
}
}
int ofset = 3;
for (int w = 0; w < 2; w++) {
if (xarray[w] == 'M' && xarray[w + ofset] == 'S') {
xmases++;
} else if (xarray[w] == 'S' && xarray[w + ofset] == 'M') {
xmases++;
}
ofset -= 2;
}
if (xmases == 2) {
return 1;
} else {
return 0;
}
}
int main() {
std::ifstream inputfile("input");
std::string input;
res = 0;
if (!inputfile.is_open()) {
std::cerr << "Could not open the file" << std::endl;
return ENOENT;
}
std::string line;
std::vector<std::vector<char>> wordsearch;
while (std::getline(inputfile, line)) {
wordsearch.push_back(std::vector<char>(line.begin(), line.end()));
}
for (int i = 0; i < wordsearch.size(); i++) {
for (int j = 0; j < wordsearch[i].size(); j++) {
if (wordsearch[i][j] == 'A') {
res += Check(wordsearch, i, j);
}
}
}
std::cout << res << std::endl;
}