Skip to content

Instantly share code, notes, and snippets.

@Florian3k
Created November 25, 2017 16:53
Show Gist options
  • Save Florian3k/2860e500ff6beaaa8e6f3efaf1e5a5b9 to your computer and use it in GitHub Desktop.
Save Florian3k/2860e500ff6beaaa8e6f3efaf1e5a5b9 to your computer and use it in GitHub Desktop.
enum class direction {
up, right, down, left
};
inline void rotate(direction& dir) {
switch (dir) {
case direction::right:
dir = direction::down;
return;
case direction::down:
dir = direction::left;
return;
case direction::left:
dir = direction::up;
return;
case direction::up:
dir = direction::right;
return;
}
}
struct position {
int x, y;
};
int findMax(int sectors[25][25], int n, position pos, direction dir) {
int from{}, to{}, step{};
if ( dir == direction::up || dir == direction::down ) {
// we are moving vertically
if ( dir == direction::up ) {
from = pos.y - 1;
to = -1;
if ( from == to ) {
return -1;
}
step = -1;
} else {
from = pos.y + 1;
to = n ;
if ( from == to ) {
return -1;
}
step = 1;
}
int col = pos.x;
int max = from;
for (int i = from; i != to; i += step ) {
if ( sectors[i][col] > sectors[max][col] ) {
max = i;
}
}
if ( sectors[max][col] == 0 ) {
return -1;
} else {
return max;
}
} else {
// we are moving horizontaly
if ( dir == direction::right ) {
from = pos.x + 1;
to = n ;
if ( from == to ) {
return -1;
}
step = 1;
} else {
from = pos.x - 1;
to = -1;
if ( from == to ) {
return -1;
}
step = -1;
}
int row = pos.y;
int max = from;
for (int i = from; i != to; i += step) {
if ( sectors[row][i] > sectors[row][max] ) {
max = i;
}
}
if ( sectors[row][max] == 0 ) {
return -1;
} else {
return max;
}
}
}
int calcLoad(int sectors[25][25], int n)
{
direction curr_dir = direction::right;
position curr_pos{0, 0};
int sum = 0;
int zerosInRow = 0;
while (zerosInRow < 4)
{
int idx = findMax(sectors, n, curr_pos, curr_dir);
if (idx == -1) {
zerosInRow++;
rotate(curr_dir);
continue;
}
if (curr_dir == direction::up || curr_dir == direction::down) {
curr_pos.y = idx;
} else {
curr_pos.x = idx;
}
sum += sectors[curr_pos.y][curr_pos.x];
sectors[curr_pos.y][curr_pos.x] = 0;
rotate(curr_dir);
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment