~cpp #include <iostream> #include <string> using namespace std; string roll( string str,int n, int i ); int getGcd(int aN, int aM); void main() { string str = "abcdefg"; int n = str.length(); int i; cout << "current : " << str << endl << "shitf amount? : "; cin >> i; cout << "after shifting : " << roll(str, n, i) << endl; } string roll( string str, int n, int i ) { if ( i % n != 0 ) i %= n; int gcd = getGcd(n, i); char temp; // for ( int count = 0 ; count * gcd < i ; count ++ ) for ( int count = 0 ; count < i ; count += gcd) for ( int tag = 0 ; tag < gcd ; tag++ ){ temp = str[tag]; for ( int base = tag ; base + gcd < n ; base += gcd) str[base] = str[base + gcd]; str[base] = temp; } return str; } int getGcd(int aN, int aM) { //assert aN > aM int remain; do{ remain = aN % aM; aN = aM; aM = remain; }while( remain != 0 ); return aN; }
~cpp #include <iostream> #include <string> using namespace std; void reverse(string & str, int start, int end); void main() { string str = "abcdefgh"; int n = str.size(); int i = 3; //shift amount int start, end; start = 0; end = i-1; reverse( str, start, end); start = i; end = n-1; reverse( str, start, end); start = 0; end = n-1; reverse( str, start, end); cout << str << endl; } void reverse(string & str, int front, int rear) { char temp; while( front < rear ){ temp = str[front]; str[front] = str[rear]; str[rear] = temp; front++; rear--; } }
~cpp #include <iostream> #include <string> using namespace std; void swap(string & str, int start1, int end1, int start2, int end2){ if ( end1 - start1 == end2 - start2){ char temp; int limit = end1 - start1 + 1; for ( int i = 0 ; i < limit ; i++){ temp = str[start1]; str[start1] = str[start2]; str[start2] = temp; start1++; start2++; } } } int main() { string str= "abcdefg"; int n = str.size(); int i = 3; // abc defg swap(str,0,i-1, n-i, n-1); // swap(str, 0, i-1, n - i, n-1); // swap(str, 0, i-1, i, n-i); cout << str << endl; return 0; }