JonsenElizee

Software Developing Blog

"An idea is fragile . It can be killed by a scornful smile or a yawn .It can be mound down by irony and scared to death by a cold look."
"Most cultures throughout human history have not liked creative individuals .They ignore them or kill them.It is a very efficient way of stopping creativity."

------Advertising boss Charles Browe and Howard Gardner ,professor at Harvard

   :: 首页 :: 新随笔 ::  ::  :: 管理 ::
Get the whole arrangement of a string.
I got no better method to get this kind of sorting sequence.
Here is a simple implementation of printing whole arrangement.
Better one is expected now...
 1 
 2 #include <assert.h>
 3 #define N 10 /* do not set a big number for n! */
 4 
 5 /**
 6  * str target string.
 7  * oka sorted content.
 8  */
 9 void pnn(char* str, char* oka)
10 {
11     /* check str */
12     assert(str != NULL && strlen(str) <= N && strlen(str) >= 1);
13     if (strlen(str) == 1) {
14         printf("%s%c\n", oka, *str);
15         return;
16     }
17     /* i to record which char need to be sort now */
18     int i = 0;
19     while(1) {
20         /* define new container for input str to swap char */
21         char ipt[N];
22         memcpy(ipt, str, strlen(str)+1);
23         /* define new container for output str to add char */
24         char opt[N];
25         memcpy(opt, oka, strlen(oka)+1);
26         /* get position of char to be sort now */
27         char* ptr = ipt + i++;
28         if(*ptr == '\0'break;
29         /* swap char with the first one in ipt */
30         if(ptr != ipt) {
31             *ptr ^= *ipt;
32             *ipt ^= *ptr;
33             *ptr ^= *ipt;
34         }
35         /* add char into opt as the last one and set '\0' to end the opt */
36         opt[strlen(oka)] = *ipt;
37         opt[strlen(oka)+1= '\0';
38         /* recursively sort next char */
39         pnn(ipt+1, opt);
40     }
41 }
42 
43 void permutation(char* str)
44 {
45     char aim[N];
46     memcpy(aim, str, strlen(str)+1);
47     char oka[1= {'\0'};
48     pnn(aim, oka);
49 }
50 
51 int main(int argc, _TCHAR* argv[])
52 {
53     permutation("1234567");
54     getchar();
55     return 0;
56 }


posted on 2010-10-20 16:48 JonsenElizee 阅读(256) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


By JonsenElizee