Day4
This commit is contained in:
BIN
day4/c/day4
Executable file
BIN
day4/c/day4
Executable file
Binary file not shown.
94
day4/c/day4.c
Normal file
94
day4/c/day4.c
Normal file
@@ -0,0 +1,94 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <omp.h>
|
||||
|
||||
#define MAX_DIMENSION 512
|
||||
|
||||
// Row, Column
|
||||
const int directions[][2] = {
|
||||
{0,1}, // Right
|
||||
{0,-1}, // Left
|
||||
{1,0}, // Down
|
||||
{-1,0}, // Up
|
||||
{1,1}, // Right-Down
|
||||
{1,-1}, // Left-Down
|
||||
{-1,-1}, // Left-Up
|
||||
{-1,1}, // Right-Up
|
||||
};
|
||||
|
||||
const char sequence[] = {'X', 'M', 'A', 'S'};
|
||||
|
||||
#define directions_len sizeof(directions) / sizeof(directions[0])
|
||||
#define sequence_len sizeof(sequence) / sizeof(sequence[0])
|
||||
|
||||
int main() {
|
||||
char *p, c;
|
||||
|
||||
int rows = 0, columns = 0;
|
||||
char **characters = calloc(MAX_DIMENSION, sizeof(characters[0]));
|
||||
characters[rows] = calloc(MAX_DIMENSION, sizeof(characters[0][0]));
|
||||
p = characters[rows];
|
||||
|
||||
while ((c = getchar()) != EOF) {
|
||||
*p++ = c;
|
||||
if (c != '\n') {
|
||||
if (rows == 0) {
|
||||
columns++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
rows++;
|
||||
characters[rows] = calloc(MAX_DIMENSION, sizeof(characters[0][0]));
|
||||
p = characters[rows];
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
int count2 = 0;
|
||||
#pragma omp parallel for
|
||||
for (int i = 0; i < rows; i++) {
|
||||
for (int j = 0; j < columns; j++) {
|
||||
for (int k = 0; k < directions_len; k++) {
|
||||
int found = 1;
|
||||
for (int l = 0; l < sequence_len; l++) {
|
||||
int row = i + l * directions[k][0];
|
||||
int column = j + l * directions[k][1];
|
||||
if (row < 0 || column < 0 || row > rows - 1 || column > columns - 1) {
|
||||
found = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
if (sequence[l] != characters[row][column]) {
|
||||
found = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found)
|
||||
#pragma omp critical
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Part2
|
||||
if (characters[i][j] == 'A' && i > 0 && i < rows - 1 && j > 0 && j < columns - 1) {
|
||||
if (
|
||||
((characters[i-1][j-1] == 'M' && characters[i+1][j+1] == 'S') || (characters[i-1][j-1] == 'S' && characters[i+1][j+1] == 'M')) &&
|
||||
((characters[i+1][j-1] == 'M' && characters[i-1][j+1] == 'S') || (characters[i+1][j-1] == 'S' && characters[i-1][j+1] == 'M'))
|
||||
)
|
||||
#pragma omp critical
|
||||
{
|
||||
count2++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < rows; i++) {
|
||||
free(characters[i]);
|
||||
}
|
||||
free(characters);
|
||||
|
||||
printf("%i\n", count);
|
||||
printf("%i\n", count2);
|
||||
}
|
||||
Reference in New Issue
Block a user