Skip to content

Instantly share code, notes, and snippets.

@maudzekod4000
Created December 16, 2024 16:48
Show Gist options
  • Save maudzekod4000/0def9d0b06bd4b46db9a6d8fcebd9f71 to your computer and use it in GitHub Desktop.
Save maudzekod4000/0def9d0b06bd4b46db9a6d8fcebd9f71 to your computer and use it in GitHub Desktop.
AOC2024 Problem 4 Part 2
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <regex>
using namespace std;
bool checkConstraints(int row, int col, int rows, int cols) {
if (row < 0 || row >= rows || col < 0 || col >= cols) {
return false;
}
return true;
}
// Helper to check if "XMAS" exists starting at (row, col) in the given direction
bool isXMASInDirection(const std::vector<std::string>& grid, int row, int col) {
if (grid[row][col] != 'A') {
return false; // In the center of MAS cross is the 'A'
}
int rows = grid.size();
int cols = grid[0].size();
// Check the top to bottom diagonal
int topLeftRow = row - 1;
int topLeftCol = col - 1;
if (!checkConstraints(topLeftRow, topLeftCol, rows, cols)) {
return false;
}
int bottomRightRow = row + 1;
int bottomRightCol = col + 1;
if (!checkConstraints(bottomRightRow, bottomRightCol, rows, cols)) {
return false;
}
bool topToBottom = false;
// Maybe we have MAS spelled from top to bottom or reverse?
if ((grid[topLeftRow][topLeftCol] == 'M' &&
grid[bottomRightRow][bottomRightCol] == 'S') ||
(grid[topLeftRow][topLeftCol] == 'S' &&
grid[bottomRightRow][bottomRightCol] == 'M')) {
topToBottom = true;
}
// Check the bottom to top diagonal /
int bottomLeftRow = row + 1;
int bottomLeftCol = col - 1;
if (!checkConstraints(bottomLeftRow, bottomLeftCol, rows, cols)) {
return false;
}
int topRightRow = row - 1;
int topRightCol = col + 1;
if (!checkConstraints(topRightRow, topRightCol, rows, cols)) {
return false;
}
// Maybe we have MAS spelled from top to bottom or reverse?
if ((grid[bottomLeftRow][bottomLeftCol] == 'M' &&
grid[topRightRow][topRightCol] == 'S') ||
(grid[bottomLeftRow][bottomLeftCol] == 'S' &&
grid[topRightRow][topRightCol] == 'M')) {
if (topToBottom) {
return true;
}
}
return false;
}
// Count all occurrences of "XMAS" in all directions
int countXMASOccurrences(const std::vector<std::string>& grid) {
int count = 0;
int rows = grid.size();
int cols = grid[0].size();
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
if (isXMASInDirection(grid, row, col)) {
++count;
}
}
}
return count;
}
int main()
{
ifstream infile("input.txt");
if (!infile.is_open()) {
cout << "File prob\n";
return -1;
}
string line;
std::vector<std::string> grid;
while (infile.good()) {
getline(infile, line);
if (line.empty()) continue;
grid.push_back(line);
}
int count = countXMASOccurrences(grid);
std::cout << count << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment