Skip to content

Instantly share code, notes, and snippets.

@PsySc0rpi0n
Last active June 5, 2016 10:05
Show Gist options
  • Save PsySc0rpi0n/2b2df71d3e81e22e25d1158a0c305680 to your computer and use it in GitHub Desktop.
Save PsySc0rpi0n/2b2df71d3e81e22e25d1158a0c305680 to your computer and use it in GitHub Desktop.
A matrix being rastered by a number
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CLEAR_INPUT while (getchar () != '\n') /*void*/
#define CLEAR_SCREEN printf ("\x1b[3;J\x1b[H\x1b[2J")
int* create_matrix(int h, int w){
int* tmp_mtx = NULL;
if ((tmp_mtx = calloc (sizeof(int), h * w)) == NULL){
printf ("Memory Error!\n");
exit (-1);
}
return tmp_mtx;
}
void rotate_value (int* mtrx, int h, int w, int* x, int* y){
mtrx[*x + (*y) * w] = 0;
(*x)++;
if ( (*x == w) && (*y == (h - 1)) ){
*x = 0, *y = 0;
} else {
if (*x == w)
(*y)++, *x = 0;
}
mtrx[*x + (*y) * w] = 8;
}
void print_matrix (int* mtrx, const int h, const int w){
for (int i = 0; i < h; i++){
for (int j = 0; j < w; j++)
printf("[%d] ", mtrx [j + i * w]);
putchar ('\n');
}
putchar ('\n');
}
void matrix_animation (int* mtrx, int h, int w, int* x, int* y){
for (int i = 0; i < h; i++){
for (int j = 0; j < w; j++){
print_matrix (mtrx, h, w);
rotate_value (mtrx, h, w, x, y);
getchar ();
printf ("\x1b[3;J\x1b[H\x1b[2J");
}
}
}
int main (int argc, char** argv){
int* matrix = NULL;
int x, y, h, w;
int check = 0;
CLEAR_SCREEN;
printf ("Matrix Width:\n");
do {
check = scanf("%d", &w);
CLEAR_INPUT;
if (check != 1)
printf ("Value not read! Try again:\n");
} while (check != 1);
printf ("Matrix Height:\n");
do {
check = scanf("%d", &h);
CLEAR_INPUT;
if (check != 1)
printf ("Value not read! Try again:\n");
} while (check != 1);
printf ("Enter starting point: <col><space><line>:\n");
while (check != 2 || x >= w || y >= h){
check = scanf("%d %d", &x, &y);
CLEAR_INPUT;
if (check != 2)
printf ("2 values required for columns and lines! Try again:\n");
if (x >= w || y >= h)
printf ("Starting point coordinates are out of bounds! Try again:\n");
}
matrix = create_matrix (h, w);
matrix[x + y * w] = 8;
CLEAR_SCREEN;
matrix_animation (matrix, h, w, &x, &y);
free (matrix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment