程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> 若何完成必定幾率選中某一個字母

若何完成必定幾率選中某一個字母

編輯:關於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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved