用 0到9 生成 十位数的所有排列组合,数字0不能在第一个,这个生成的十位数,
不能有重复的数字。
public static void main(String[] args) {
String str[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
permutation(str, 0, str.length);
}
static void swap(String[] str, int start, int end) {
String tmep = str[start];
str[start] = str[end];
str[end] = tmep;
}
static void permutation(String[] str, int start, int end) {
if (start == end - 1) {
for (int i = 0; i < end; i++) {
System.out.print(str[i]);
}
System.out.println();
} else {
for (int i = start; i < end; i++) {
if (i == 0 && str[0].equals("0"))
continue;
swap(str, start, i);
permutation(str, start + 1, end);
swap(str, start, i);
}
}
}
}
C语言版本的
unsigned char str[10];
unsigned char str_file[10];
unsigned int count;
FILE fp;
/用0到9这十个数字 所有的排列组合(0不能再第一个) 1C
用 0到9 生成 十位数的所有排列组合,数字0不能在第一个,这个生成的十位数,*/
void print(unsigned char* str1,int count)
{
int i;
for(i=0;i<count;i++)
{
printf("%d",str1[i]);
str_file[i]=str1[i]+0x30;
}
printf("\n");
}
void group(int offset,unsigned char* buffer,int depth)
{
int j,k;
unsigned char tvalue;
unsigned char* ptr;
if(depth==2)
{
ptr=str+offset;
memcpy(ptr,buffer+offset,depth);
for(k=0;k<depth;k++)
{
tvalue=ptr[0];
for(j=0;j<(depth);j++)
ptr[j]=ptr[j+1];
ptr[depth-1]=tvalue;
if(str[0]!=0)
{
//print(str,depth+offset);
//printf("\n");
fwrite(str_file, sizeof( char ),depth+offset,fp); //14
fwrite("\x0d\x0a", sizeof( char ),2,fp);
count++;
}
}
}
else
{
ptr=buffer+offset;
memcpy(str+offset,ptr,depth);
for(k=0;k<depth;k++)
{
str[offset]=ptr[0];
ptr++;
depth--;
memcpy(str+offset+1,ptr,depth);
group(offset+1,buffer,depth);
ptr--;
depth++;
tvalue=ptr[k];
for(j=0;j<(depth);j++)
ptr[(k+j)%depth]=ptr[((k+j+1)%depth)];
ptr[(k+depth-1)%depth]=tvalue;
}
}
return;
}
int main(int argc, char* argv[])
{
unsigned char num[10]={0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09};
char bmpName[50]={"./test.txt"};
count=0;
fp=fopen(bmpName,"wb");
if(fp==NULL)
{
fclose(fp);
printf("文件打开失败");
return 0;
}
fseek(fp,0,SEEK_SET);
//group(0,num,2);
//group(0,num,3);
group(0,num,10);
printf("一共%d组",count);
printf("\n");
strcpy((char*)str_file,"一共");
itoa((int)count,(char*)str_file+4,10);
strcpy((char*)str_file+8,"组");
fwrite(str_file, sizeof( char ),10,fp); //14
fwrite("\x0d\x0a", sizeof( char ),2,fp);
//关闭文件
fclose(fp);
return 0;
}