亲宝软件园·资讯

展开

概率 字母 怎样实现一定概率选中某一个字母

人气:0
想了解怎样实现一定概率选中某一个字母的相关内容吗,在本文为您仔细讲解概率 字母的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:概率,字母,下面大家一起来学习吧。
在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;
}

加载全部内容

相关教程
猜你喜欢
用户评论