闲来没事做,写个模拟中奖的生成程序,程序的思路是用随机数产生器随机产生两个字符串数组,每个字符串数组又分为N个子字符串,如果这两个组里面有任何俩个子字符串是相同的,就作为中奖号码
#include<iostream> #include<string> #include<ctime> #include<vector> #include<cassert> #include<cstring> #include<windows.h> #include<algorithm> using namespace std; vector<string> sets1,sets2,sets3;//用来保存字符串集合 void product(vector<string>&sets,int num1,int num2)//num1传入每个字符串的长度,num2传入字符集中字符串的个数 { for(int s=0;s<num2;++s) { string s; char ch; for(int i=0;i<num1;++i) { int x=rand()%10; ch=x+48; s+=ch; } sets.push_back (s);// 将字符串放入字符集中 } } bool CompareStrings(string &s1,string &s2) { bool tag=true; if(s1.size() ==s2.size()) { for(int i=0;i<s1.size ();++i) { if(s1[i]!=s2[i]) { tag=false; break; } } } else tag=false; return tag; } int main() { int StringLength=0;//用来指定每个字符串的长度 int StringsNumbers=0;//用来指定2个字符集中字符串的个数 cout<<\"请输入字符串集的字符串的个数:\"<<endl; cin>>StringsNumbers; assert(StringsNumbers>0); cout<<\"请输入每个字符串的长度:\"<<endl; cin>>StringLength; assert(StringLength>0); srand((unsigned)time(0));//设定种子为时间 product(sets1,StringLength,StringsNumbers); product(sets2,StringLength,StringsNumbers); stable_sort(sets1.begin (),sets1.end ());//对字符集排序 stable_sort(sets2.begin (),sets2.end ()); // cout<<\"集合1的字符串为:\"<<endl; // vector<string>::iterator iter1=sets1.begin (); // for( ;iter1!=sets1.end ();++iter1) [Page] // cout<<*iter1<<endl; // cout<<\"集合2的字符串为:\"<<endl; // vector<string>::iterator iter2=sets2.begin (); // for( ;iter2!=sets2.end ();++iter2) // cout<<*iter2<<endl; int i=0; int j=0; int k=0; while(i<sets1.size ()&&j<sets2.size ()&&k<StringLength) { if(sets1[i][k]<sets2[j][k]&&i<sets1.size ()) { ++i; k=0; } else if(sets1[i][k]>sets2[j][k]&&j<sets2.size ()) { ++j; k=0; } else//如果sets1[i][k]==sets2[j][k],那么比较sets1[i][k+1]和sets2[j][k+1] { ++k; if(k==StringLength&&i<sets1.size ()) { sets3.push_back (sets1[i]); if(i<sets1.size ()) ++i; if(j<sets2.size ()) ++j; k=0; } }//else }//while if(sets3.empty ()) cout<<\"没有公共字符串! \"<<endl; else { cout<<\"公共字符串为:\"<<endl; vector<string>::iterator it=sets3.begin (); for(;it!=sets3.end ();++it) cout<<*it<<endl; } return 0; } |