Skip to content

Instantly share code, notes, and snippets.

@maudzekod4000
Created December 18, 2024 22:01
Show Gist options
  • Save maudzekod4000/3efbfbe80585415c185af50da43e3dbc to your computer and use it in GitHub Desktop.
Save maudzekod4000/3efbfbe80585415c185af50da43e3dbc to your computer and use it in GitHub Desktop.
Big beard AOC 2024 Day 6 Part 1
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <regex>
#include <utility>
using namespace std;
enum Dir {
UP, RIGHT, DOWN, LEFT
};
struct Vec {
Vec(int x, int y, Dir d) : x(x), y(y), d(d) {}
int x;
int y;
Dir d;
};
void markGuardSteps(std::vector<std::string>& grid, int x, int y, int rows, int cols)
{
Vec up(-1, 0, UP);
Vec right(0, 1, RIGHT);
Vec down(1, 0, DOWN);
Vec left(0, -1, LEFT);
Vec currentDir = up;
int prevx = x;
int prevy = y;
while (x >= 0 && y >= 0 && x < rows && y < cols) {
// While we are in the bounds of the grid, keep marking the steps.
char currentTerrain = grid[x][y];
if (currentTerrain != '#') {
grid[x][y] = 'X';
}
else {
// We have hit a crate
// Get to the previous position and change the direction to the right.
x = prevx;
y = prevy;
if (currentDir.d == UP) {
currentDir = right;
}
else if (currentDir.d == RIGHT) {
currentDir = down;
}
else if (currentDir.d == DOWN) {
currentDir = left;
}
else {
currentDir = up;
}
}
// store the previous position
prevx = x;
prevy = y;
// Apply the direction with speed 1 cell
x += currentDir.x;
y += currentDir.y;
}
}
int countMarked(std::vector<std::string>& grid)
{
int count = 0;
for (auto& str : grid) {
for (char c : str) {
if (c == 'X') {
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;
int guardx = 0, guardy = 0;
int lineCount = 0;
int colsCount = 0;
while (infile.good()) {
getline(infile, line);
if (line.empty()) break;
auto pos = line.find('^');
if (pos != -1) {
guardx = lineCount;
guardy = pos;
colsCount = line.size();
}
grid.push_back(line);
lineCount++;
}
markGuardSteps(grid, guardx, guardy, grid.size(), colsCount);
int a = countMarked(grid);
std::cout << a << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment