欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

如何实现一定概率选中某一个字母

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

在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语言

下一篇:解决不用sizeof求出int大小的方法

本文标题:如何实现一定概率选中某一个字母

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/4373.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有