n 元一维向量旋转问题(编程珠机) 第二章问题B
2012-07-12 14:48
411 查看
/* * method No_1 * using a temp to store x[0],then x[0] = x[i] ,x[i] = x[2i] ......until ki>=n,then x[(k-1)i] = x[0] * then dealing with x[1],x[2] ........x[i-1] */ int gcd(int x ,int y) { if(x==0)return y; if(y==0)return x; if(x>y)return gcd(x%y,y); return gcd(x,y%x); } void vector_reversal(char* str, int n, int rotdist) { int len = gcd(n,rotdist); int i; for(i =0;i<len;i++) { int temp = str[i]; int j = i; while(1) { int k = j+rotdist; if(k>=n) k-=n; if(k==i) break; str[j] = str[k]; j = k; } str[j] = temp; } } /* * method No_2 * recursive the programming requirs that we can reversal vector ab into ba, so if len(a) < len(b),we can divide b into b1,b2, * the vector will be ab1b2,and len(a) == len(b2),swap the memory a and b2,the vector changes to be b2b1a, and a has located at right * place ,the next is to deal with b2b1,which is suposed be b1b2,so , it's very easy to solve it with a recursive programme * the method is same to dealing with len(a)<(len)b, when len(a) > len(b), and when len(a) == len(b) ,swap the memory */ void swap(char *p1_start,char *p2_start,int len) { while(len--) { char temp = p1_start[len]; p1_start[len] = p2_start[len]; p2_start[len] = temp; } } void vector_reversal(char *base,int n, int i) { if(i == n-i) { swap(base,base+i,i); return ; } if(i < n-i) { swap(base,base+n-i,i); vector_reversal(base,n-i,i); } else{ swap(base+2*i-n,base+i,n-i); vector_reversal(base,i,2*i-n); } } /* * methond No_3 , two times reversal * the vector is ab,which is supposed to be changed into ba, * so reverse a into a' , change b into b' ,then change (a'b') into (a'b')' = ba */ void swap(char *a,char *b) { char temp = *a; *a = *b; *b = temp; } void reversal(char *start,char *end) { char *ptr_start = start; char *ptr_end = end; while(ptr_start < ptr_end) { swap(ptr_start,ptr_end); ptr_start++; ptr_end--; } } void vector_reversal(char *base,int n, int i) { reversal(base,base+i-1); reversal(base+i,base+n-1); reversal(base,base+n-1); }
相关文章推荐
- 编程珠玑第二章问题B: n元一维向量旋转问题之java实现
- 编程珠玑之第二章questionB: n元一维向量旋转问题
- 问题:将一个n元一维向量向左旋转i个位置,例如,当n=8且i=3时,向量abcdefgh旋转为defghabc。
- 编程珠玑---第二章---n元一维向量向左旋转
- n元一维向量旋转问题
- {Programming Pearls}第二章--向量旋转问题
- 编程珠玑2章B问题--n元一维向量向左旋转i个位置
- 一维向量旋转算法 编程珠玑 第二章
- n元一维向量旋转问题(编程珠玑--第2章--问题B )
- 平移向量:将一个具有n个元素的一维向量向左旋转i个位置
- n元一维向量向左旋转i个位置
- 三角形外接圆的圆心,向量旋转问题,求点(x1,y1)绕点(0,0)旋转a后坐标
- HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数
- 《编程珠玑(第2版)》笔记——将一个n元一维向量向左旋转i个位置(第2章)
- HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数
- C++实现一维向量旋转算法
- 一维向量旋转算法
- 向量旋转问题
- 《编程珠玑(第2版)》笔记——将一个n元一维向量向左旋转i个位置(第2章)
- 编程珠玑(1):将一个n元一维向量向左旋转i个位置。例如当n=8且i=3时,向量abcdefgh 旋转为defghabc