Skip to content

Instantly share code, notes, and snippets.

@maudzekod4000
Created December 16, 2024 16:16
Show Gist options
  • Select an option

  • Save maudzekod4000/a442f375dafc5cb925e9cbfb49004781 to your computer and use it in GitHub Desktop.

Select an option

Save maudzekod4000/a442f375dafc5cb925e9cbfb49004781 to your computer and use it in GitHub Desktop.
Hail ChatGPT AOC 2024-Problem 4 Part 1
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <regex>
using namespace std;
// 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, int dRow, int dCol) {
const std::string target = "XMAS";
int rows = grid.size();
int cols = grid[0].size();
for (int i = 0; i < target.size(); ++i) {
int newRow = row + i * dRow;
int newCol = col + i * dCol;
// Check bounds
if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) {
return false;
}
// Check if the current character matches
if (grid[newRow][newCol] != target[i]) {
return false;
}
}
return true;
}
// 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();
// Define all 8 directions (row, col deltas)
const std::vector<std::pair<int, int>> directions = {
{0, 1}, // Right
{1, 0}, // Down
{0, -1}, // Left
{-1, 0}, // Up
{1, 1}, // Down-Right (Diagonal)
{1, -1}, // Down-Left (Diagonal)
{-1, 1}, // Up-Right (Diagonal)
{-1, -1} // Up-Left (Diagonal)
};
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
for (const auto& [dRow, dCol] : directions) {
if (isXMASInDirection(grid, row, col, dRow, dCol)) {
++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