百度面试题----依概率生成

一、编程题(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);
}
小人本潜水在思源的贴边
ID又多 又有钱
快活乐无边
谁知道站总监
他蛮横不留情面
他勾结站长目无天
占我ID夺我钱
我马甲跟他来翻脸
反被他来把经验减
我同学骂他欺新人
反被他捉进了小黑屋里面
874了一百遍啊一百遍
啊 最后他咬舌自尽 遗恨人间
他还将我和马甲赶出了思源 流落在人间
我为求回思源
无奈行乞在贴前
谁知道站总监他实在太阴险
知道此情形竟派人来暗算将我发文狂删到0篇
小人ID强 残命独留全
可怜马甲他 竟遭删
为求养ID
惟有傍人卖身自作践
一面苦赚钱 一面写诗篇
发誓把名气显
手刃总监意志坚啊
从此总监ID念心间
我永铭记此仇不供戴天
原文地址:https://www.cnblogs.com/CUCmehp/p/1497966.html