Fast algorithm C code for full letter arrangement

Source: Internet
Author: User
Tags count int size strlen

All arranged, such as ABC of letters, all arranged with a, AB,AC,ABC,ACB,B,BA,BC,BAC,BCA,C,CA,CB,CAB,CBA.

The principle is to insert new characters in all positions of a string.
such as: AB insert C, position has 1a2b3, insert after the formation of CAB ACB ABC
Char *alllist (char *str, int *pnum)
... {
int I, j, K, N;
int len = strlen (str);
int total = 0;
int count, Oldcount;
int size;
Char *buf;
Char *p, *P1;
if (Len >) return NULL;
Calculates the total number of combinations
for (i = 0, j = 1; i < Len; i++)
... {
J *= (Len-i);
Total = j;
}
Create a two-dimensional array that holds all the combinations
size = len + 1;
if ((Buf = (char *) malloc (total * size) = = NULL)
... {
return NULL;
}
for (k = 0, count = 0; k < len; k++)//all characters to insert
... {
Oldcount = count;
p = Buf;
P1 = Buf + count * size;
for (i = 0; i < oldcount; i++, p + = size)//INSERT into all strings to form a new string
... {
n = strlen (p);
for (j = 0; J <= N; j + +, count++, p1 = size)//Insert all positions in string
... {
memcpy (P1, p, N);
P1[n] = P1[j];
P1[J] = str[k];
P1[n + 1] = '

Arrange 10 letters on my machine for about 0.5 seconds.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.