Last active
March 21, 2016 20:07
-
-
Save alvarezp/0d4bd4a111efb76fb486 to your computer and use it in GitHub Desktop.
Cyclic Rotation: C, O(n) compute, O(n) memory, input data immutable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int mod(int a, int b) { | |
if (a == 0) | |
return 0; | |
if (a > 0 && b > 0) { | |
return a % b; | |
} | |
if (a < 0 && b > 0) { | |
return (b - ((-a) % b)) % b; | |
} | |
if (a > 0 && b < 0) { | |
return ((-b) - (a % (-b))) % (-b); | |
} | |
if (a < 0 && b < 0) { | |
return (-a) % (-b); | |
} | |
// Aquí debería regresar un error porque b == 0 | |
// pero no es el punto en este ejercicio. | |
return 99; | |
} | |
int * rotateA(const int src[], const int src_n, const int rot_n) { | |
int real_rot; | |
int si, di; | |
if (src_n == 0) | |
return NULL; | |
int * ret = malloc(sizeof(int) * src_n); | |
if (ret == NULL) | |
return NULL; | |
if (rot_n == 0) | |
return memcpy(ret, src, sizeof(int) * src_n); | |
real_rot = mod(rot_n, src_n); | |
for (di = 0, si = src_n - real_rot; si < src_n; si++, di++) { | |
ret[di] = src[si]; | |
} | |
for (si = 0; si < src_n - real_rot; si++, di++) { | |
ret[di] = src[si]; | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment