如何实现一定概率选中某一个字母_C语言教程-查字典教程网
如何实现一定概率选中某一个字母
如何实现一定概率选中某一个字母
发布时间:2016-12-28 来源:查字典编辑
摘要:在C#版看到这一篇文章,手边现在正开著MacBook上网实在不太想重新开Windows跟VisualStudio来编码正好我也在练习C++T...

在C#版看到这一篇文章,手边现在正开著MacBook上网

实在不太想重新开Windows跟Visual Studio来编码

正好我也在练习C++ Template,那就很刚好试著用Template来实践一下

复制代码 代码如下:

//

// main.cpp

// RandomTest

//

// Created by Cloud on 2011/4/10.

// Copyright 2011年 Orz. All rights reserved.

//

#include <iostream>

#include <vector>

using namespace std;

template<class T>

class RandomWord

{

T m_Word;

int m_Probability;

public:

RandomWord(T word, int probability):m_Word(word),m_Probability(probability){}

T getWord() { return m_Word; }

int getProbability() { return m_Probability; }

};

template<class T>

class RandManager

{

vector<RandomWord<T> > m_randomList;

int m_sumOfProbability;

public:

RandManager() :m_randomList(), m_sumOfProbability(0)

{

}

void AddRandomWord(RandomWord<T> word)

{

if(m_sumOfProbability <= 100)

m_randomList.push_back(word);

cout<<"Add word:"<<word.getWord()<<endl;

cout<<"Probability:"<<m_sumOfProbability;

cout<<"-"<<word.getProbability() + m_sumOfProbability<<endl;

m_sumOfProbability += word.getProbability();

}

void RandomGenerate(int randNum)

{

cout<<"Random:"<<randNum<<endl;

int sum = 0;

for(int i = 0 ; i < m_randomList.size() ; i++)

{

RandomWord<T> orz = m_randomList[i];

if( (sum <= randNum) && (randNum < (orz.getProbability() + sum)))

{

cout<<"Generate:"<<orz.getWord()<<endl;

break;

}

else

{

sum += orz.getProbability();

}

}

}

};

int main (int argc, const char * argv[])

{

RandManager<char> manager;

manager.AddRandomWord(RandomWord<char>('A',10));

manager.AddRandomWord(RandomWord<char>('B',10));

manager.AddRandomWord(RandomWord<char>('C',35));

manager.AddRandomWord(RandomWord<char>('D',25));

manager.AddRandomWord(RandomWord<char>('E',20));

srand(time(NULL));

manager.RandomGenerate(rand()%100);

return 0;

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新C语言学习
    热门C语言学习
    编程开发子分类