一、编程题(30分)
输入:N(整数)
输入:数据文件A.txt,不超过6条记录,字符串长度不超过15个字节
文件格式如下:
字符串\t数字\n
说明:
每行为1条记录;字符串中不含有\t。
数字描述的是该字符串的出现概率,小于等于100的整数。
多条记录的出现概率之和为100,如果A.txt不满足该条件,程序则退出;
如果文件格式错误,程序也退出。
要求:
编写一个程序,输入为N(正整数),读入文件A.txt,按照字符串出现概率随机地输出字符串,输出N条记录
例如:
输入文件A.txt
abc\t20
a\t30
de\t50
输入为:10
即 abc有20%的概率输出,a有30%的概率输出,de有50%的概率输出,输出10条记录
以下为一次输出的结果,多次输出的结果可能不相同。
abc
a
de
de
abc
de
a
de
a
de
说明:刚看到题时,把\t理解成了字符串。最后觉得应该是tab键。
因此程序在输入时,读的是下述这种文件格式:
abc\t20
a\t30
de\t50
题目属于基础编程,程序注释挺多的,就不多解释了
#include<fstream>
#include<iostream>
#include<map>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
#include<time.h>
using namespace std;
typedef map<string,int> Str_List;
//检查总概率是否为100
bool checkTotalSum(Str_List list){
double sum=0;
for(Str_List::iterator it=list.begin();it!=list.end();it++){
sum+=(*it).second;
}
if(sum==100)
return true;
return false;
}
int main(){
//初始化随机数种子
srand(time(0));
int n;
cin>>n;
Str_List list=Str_List();
ifstream fin("A.txt",ios::in);
string str;
//将A.txt读入list中
while(fin>>str){
int index=str.find_first_of("\\t");
string temp_str=str.substr(0,index);
string temp_value=str.substr(index+2,str.size()-index);
stringstream ss("");
ss<<temp_value;
double temp;
ss>>temp;
list.insert(make_pair(temp_str,temp));
}
if(!checkTotalSum(list))
return -1;
vector<string> vec;
int index=0;
for(Str_List::iterator it=list.begin();it!=list.end();it++){
index+=(*it).second;
for(int i=0;i<(*it).second*n/100;i++){
vec.push_back((*it).first);
}
}
//如果少了一个,就把第一个串加一次
if(index<n){
vec.push_back((*list.begin()).first);
}
//随机重排
random_shuffle(vec.begin(),vec.end());
ostream_iterator<string> os(cout,"\n");
copy(vec.begin(),vec.end(),os);
}
#include<iostream>
#include<map>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
#include<time.h>
using namespace std;
typedef map<string,int> Str_List;
//检查总概率是否为100
bool checkTotalSum(Str_List list){
double sum=0;
for(Str_List::iterator it=list.begin();it!=list.end();it++){
sum+=(*it).second;
}
if(sum==100)
return true;
return false;
}
int main(){
//初始化随机数种子
srand(time(0));
int n;
cin>>n;
Str_List list=Str_List();
ifstream fin("A.txt",ios::in);
string str;
//将A.txt读入list中
while(fin>>str){
int index=str.find_first_of("\\t");
string temp_str=str.substr(0,index);
string temp_value=str.substr(index+2,str.size()-index);
stringstream ss("");
ss<<temp_value;
double temp;
ss>>temp;
list.insert(make_pair(temp_str,temp));
}
if(!checkTotalSum(list))
return -1;
vector<string> vec;
int index=0;
for(Str_List::iterator it=list.begin();it!=list.end();it++){
index+=(*it).second;
for(int i=0;i<(*it).second*n/100;i++){
vec.push_back((*it).first);
}
}
//如果少了一个,就把第一个串加一次
if(index<n){
vec.push_back((*list.begin()).first);
}
//随机重排
random_shuffle(vec.begin(),vec.end());
ostream_iterator<string> os(cout,"\n");
copy(vec.begin(),vec.end(),os);
}