首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎样生成随机的26字母的排列解决办法

2012-03-24 
怎样生成随机的26字母的排列我想生成一数组,要求数组里每一元素都为26个字母其中的一个,数组大小为26,也就

怎样生成随机的26字母的排列
我想生成一数组,要求数组里每一元素都为26个字母其中的一个,数组大小为26,
也就是说需要一个随机排列的字母表,该怎么生成啊?

[解决办法]
#include <iostream.h>
char (*p)[27];
template <class Type>
void perm(Type list[],int k,int m,int n)
{
int size=n;
if(!(p=(char *)malloc(size*27*sizeof(char)))exit(1);
if(k==m)
{
for(int i=0;i <=m;i++)
if(list[i]!=-1){
if(*(p+27)==NULL){
p=(char *)malloc((size++)*27*sizeof(char));
}
*((p+size)+i))=list[i];
}
*((p+size)+27)= '\0 ';
}
else
for(int i=k;i <=m;i++)
{
swap(list[k],list[i]);
perm(list,k+1,m);
swap(list[k],list[i]);
}
}
template <class Type>
inline void swap(Type & a,Type & b)
{
Type temp=a;a=b;b=temp;
}
//template <class Type>
void main()
{
int l[27];
for(int i=0;i <26;i++)
l[i]= 'a '++;
l[27]= '0 ';
perm(l,0,4,1);
for(int i=0;i <26;i++)
cout < <l[rand()%27][i];
}
[解决办法]
char ch[26],result[26],;
for (int i = 0;i <26;i++) ch[i] = 'A ' + i;
for (int i = 0;i <26;i++)
{
idx = rand()%(26-i);
result[i] = ch[idx];
ch[idx] = ch[25-i];
}

完毕,result是你要的结果,随机种子自己设。
[解决办法]
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <list>
using namespace std;
int main()
{
char result[26];
list <char> alist;
for(int i=0;i <26;i++)
{
alist.push_back(char( 'a '+i));
}
int i=26;
for(;;)
{
list <char> ::iterator it=alist.begin();
srand((unsigned)time(NULL));
int times=rand()%i+1;
for(int j=0;j <(times-1);j++)
{
it++;
}
result[26-i]=*it;
alist.erase(it);
i--;
if(i==0)
break;
}
for(int k=0;k <26;k++)
cout < <result[k];
system( "pause ");
return 0;
}

[解决办法]
STL里的permulation算法能帮你的忙
[解决办法]

STL里的random_shuffle算法,现成的。

热点排行