Last active
August 29, 2015 14:14
-
-
Save gwang/39ffce190d7d3a98b8b8 to your computer and use it in GitHub Desktop.
Rotate a potentially large string about a pivot point
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
#include <stdlib.h> | |
#include <stdio.h> | |
void reverse(char *data, int start, int end) | |
{ | |
int i; char tmp; | |
for (i=0; i<(end-start)/2; i++) | |
{ | |
tmp = data[i+start]; | |
data[i+start] = data[end-i-1]; | |
data[end-i-1] = tmp; | |
} | |
} | |
void rotate(char *data, int pivot) | |
{ | |
int i, j, l, f; | |
char tmp; | |
l = strlen(data); | |
printf("length = %d\n", l); | |
for (i=0; i<pivot; i++) | |
{ | |
tmp = data[i]; | |
f = i; | |
j = i + pivot; | |
while (j<=l-pivot+i) | |
{ | |
if (i == 0 ) printf("f= %d, j = %d\n", f, j); | |
data[f] = data[j]; | |
f = j; | |
j += pivot; | |
} | |
data[f] = tmp; | |
printf("%s.\n", data); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
char data[] = "The quick brown fox jumps over the lazy dog."; | |
/* test solution #1 */ | |
reverse(data, 0, 4); | |
reverse(data, 4, strlen(data)); | |
reverse(data, 0, strlen(data)); | |
printf("test 1 = '%s'\n", data); /* should be 'quick brown fox jumps over the lazy dog.The ' */ | |
/* test solution #2 */ | |
rotate(data, 6); | |
printf("test 2 = '%s'\n", data); /* should be 'quick brown fox jumps over the lazy dog.The quick ' */ | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment