Skip to content

Instantly share code, notes, and snippets.

@alivesay
Created May 20, 2021 16:04
Show Gist options
  • Save alivesay/da0a7e0c2baa6608ea4ddef152e2086a to your computer and use it in GitHub Desktop.
Save alivesay/da0a7e0c2baa6608ea4ddef152e2086a to your computer and use it in GitHub Desktop.
inline bool contains(int x, int y, Bounds rect) {
return (x <= rect.right) && (y <= rect.bottom) && (x >= rect.left) && (y >= rect.top);
}
void BuildStringFromMatrix(int* Matrix, int NumRows, int NumColumns, char* OutBuffer) {
Bounds rect = { NumColumns - 1 , NumRows - 1, 0, 0 };
int dir = 0;
int count = 0;
int x = 0;
int y = 0;
while (++count < NumRows * NumColumns) {
OutBuffer += sprintf(OutBuffer, "%d, ", Matrix[x + NumColumns * y]);
// move
switch (dir % 4) {
case 0: if (contains(++x,y,rect)) break; else x--; dir++; rect.top++; // right
case 1: if (contains(x,++y,rect)) break; else y--; dir++; rect.right--; // down
case 2: if (contains(--x,y,rect)) break; else x++; dir++; rect.bottom--; // left
case 3: if (contains(x,--y,rect)) break; else y++; dir++; rect.left++; // up
default: ++x;
};
}
OutBuffer += sprintf(OutBuffer, "%d", Matrix[x + NumColumns * y]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment