aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

day04a.cpp (1961B)


      1 #include <algorithm>
      2 #include <iostream>
      3 #include <sstream>
      4 #include <string>
      5 #include <string_view>
      6 #include <vector>
      7 using namespace std;
      8 
      9 enum class Direction { U, D, R, L, UR, UL, DR, DL };
     10 Direction all_directions[] = {
     11 	Direction::U, Direction::D, Direction::R, Direction::L,
     12 	Direction::UR, Direction::UL, Direction::DR, Direction::DL
     13 };
     14 
     15 pair<int, int> step(pair<int, int> p, Direction d) {
     16 	auto [i, j] = p;
     17 
     18 	switch (d) {
     19 	case Direction::U:
     20 		return make_pair(i-1, j);
     21 	case Direction::D:
     22 		return make_pair(i+1, j);
     23 	case Direction::R:
     24 		return make_pair(i, j+1);
     25 	case Direction::L:
     26 		return make_pair(i, j-1);
     27 	case Direction::UR:
     28 		return make_pair(i-1, j+1);
     29 	case Direction::UL:
     30 		return make_pair(i-1, j-1);
     31 	case Direction::DR:
     32 		return make_pair(i+1, j+1);
     33 	case Direction::DL:
     34 		return make_pair(i+1, j-1);
     35 	}
     36 
     37 	return make_pair(-999,-999);
     38 }
     39 
     40 class Board {
     41 public:
     42 	int M, N;
     43 
     44 	Board(vector<string> &lines) {
     45 		N = lines.size();
     46 		M = 0;
     47 		for (string l : lines)
     48 			M = max(M, (int)l.size());
     49 		cells = new char[M * N];
     50 		for (int i = 0; i < N; i++)
     51 			for (int j = 0; j < M; j++)
     52 				cells[M*i + j] = j < (int)lines[i].size() ?
     53 				    lines[i][j] : out_of_bound;
     54 	}
     55 
     56 	string word_at(int i, int j, Direction d, int l) {
     57 		string ret = "";
     58 		auto p = make_pair(i, j);
     59 		for (int k = 0; k < l; k++, p = step(p, d))
     60 			ret += (*this)[p];
     61 		return ret;
     62 	}
     63 
     64 	~Board() {
     65 		delete []cells;
     66 	}
     67 
     68 private:
     69 	const char out_of_bound = '.';
     70 	char *cells;
     71 
     72 	char operator[](pair<int, int> p) {
     73 		auto [i, j] = p;
     74 		if (i >= N || i < 0 || j >= M || j < 0)
     75 			return out_of_bound;
     76 		return cells[M*i + j];
     77 	}
     78 };
     79 
     80 int main() {
     81 	string line;
     82 	vector<string> lines;
     83 	while (getline(cin, line))
     84 		lines.push_back(line);
     85 
     86 	Board board(lines);
     87 	int tot = 0;
     88 	for (int i = 0; i < board.N; i++)
     89 		for (int j = 0; j < board.M; j++)
     90 			for (Direction d : all_directions)
     91 				if (board.word_at(i, j, d, 4) == "XMAS")
     92 					tot++;
     93 	cout << tot << endl;
     94 
     95 	return 0;
     96 }