1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-16 20:56:57 +02:00
CodeWars/4kyu/snail/solution.cs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

46 lines
1,010 B
C#

using System;
public class SnailSolution {
private static void Update(ref int dx, ref int dy) {
int newDx = -dy, newDy = dx;
dy = newDy;
dx = newDx;
}
public static int[] Snail(int[][] array) {
if (array.Length == 1 && array[0].Length == 0) {
return new int[] {};
}
int[] result = new int[array.Length * array.Length];
int y = 0, x = 0;
int dy = 0, dx = 1;
int left = -1, right = array.Length;
int top = 0, bottom = array.Length;
for (var i = 0; i < result.Length; i++) {
result[i] = array[y][x];
if (dx != 0 && x + dx <= left) {
left++;
Update(ref dx, ref dy);
} else if (dx != 0 && x + dx >= right) {
right--;
Update(ref dx, ref dy);
} else if (dy != 0 && y + dy <= top) {
top++;
Update(ref dx, ref dy);
} else if (dy != 0 && y + dy >= bottom) {
bottom--;
Update(ref dx, ref dy);
}
x += dx;
y += dy;
}
return result;
}
}