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

时间:2022-06-27 06:24:11

在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;
}