c#中獎演算法的實現

来源:http://www.cnblogs.com/ahjesus/archive/2016/11/07/6038015.html
-Advertisement-
Play Games

演算法名稱 Alias Method 測試 最後推薦個站,全世界的手機號碼免費使用 天神號碼www.ahjesus.com ...


演算法名稱 Alias Method

public class AliasMethod {
        /* The probability and alias tables. */
        private int[] _alias;
        private double[] _probability;

        public AliasMethod(List<Double> probabilities) {

            /* Allocate space for the probability and alias tables. */
            _probability = new double[probabilities.Count];
            _alias = new int[probabilities.Count];

            /* Compute the average probability and cache it for later use. */
            double average = 1.0 / probabilities.Count;

            /* Create two stacks to act as worklists as we populate the tables. */
            var small = new Stack<int>();
            var large = new Stack<int>();

            /* Populate the stacks with the input probabilities. */
            for (int i = 0; i < probabilities.Count; ++i) {
                /* If the probability is below the average probability, then we add
                 * it to the small list; otherwise we add it to the large list.
                 */
                if (probabilities[i] >= average)
                    large.Push(i);
                else
                    small.Push(i);
            }

            /* As a note: in the mathematical specification of the algorithm, we
             * will always exhaust the small list before the big list.  However,
             * due to floating point inaccuracies, this is not necessarily true.
             * Consequently, this inner loop (which tries to pair small and large
             * elements) will have to check that both lists aren't empty.
             */
            while (small.Count > 0 && large.Count > 0) {
                /* Get the index of the small and the large probabilities. */
                int less = small.Pop();
                int more = large.Pop();

                /* These probabilities have not yet been scaled up to be such that
                 * 1/n is given weight 1.0.  We do this here instead.
                 */
                _probability[less] = probabilities[less] * probabilities.Count;
                _alias[less] = more;

                /* Decrease the probability of the larger one by the appropriate
                 * amount.
                 */
                probabilities[more] = (probabilities[more] + probabilities[less] - average);

                /* If the new probability is less than the average, add it into the
                 * small list; otherwise add it to the large list.
                 */
                if (probabilities[more] >= average)
                    large.Push(more);
                else
                    small.Push(more);
            }

            /* At this point, everything is in one list, which means that the
             * remaining probabilities should all be 1/n.  Based on this, set them
             * appropriately.  Due to numerical issues, we can't be sure which
             * stack will hold the entries, so we empty both.
             */
            while (small.Count > 0)
                _probability[small.Pop()] = 1.0;
            while (large.Count > 0)
                _probability[large.Pop()] = 1.0;
        }

        /**
         * Samples a value from the underlying distribution.
         *
         * @return A random value sampled from the underlying distribution.
         */
        public int next() {

            long tick = DateTime.Now.Ticks;
            var seed = ((int)(tick & 0xffffffffL) | (int)(tick >> 32));
            unchecked {
                seed = (seed + Guid.NewGuid().GetHashCode() + new Random().Next(0, 100));
            }
            var random = new Random(seed);
            int column = random.Next(_probability.Length);

            /* Generate a biased coin toss to determine which option to pick. */
            bool coinToss = random.NextDouble() < _probability[column];

            return coinToss ? column : _alias[column];
        }
    }

測試

Dictionary<String, Double> map = new Dictionary<String, Double>();
            map.Add("1金幣", 0.2);
            map.Add("2金幣", 0.15);
            map.Add("3金幣", 0.1);
            map.Add("4金幣", 0.05);
            map.Add("未中獎", 0.5);

            List<Double> list = new List<Double>(map.Values);
            List<String> gifts = new List<String>(map.Keys);

            AliasMethod method = new AliasMethod(list);

            Dictionary<String, int> resultMap = new Dictionary<String, int>();

            for (int i = 0; i < 10; i++) {
                int index = method.next();
                string key = gifts[index];
                Console.WriteLine(index+":"+key);
            }

最後推薦個站,全世界的手機號碼免費使用 天神號碼www.ahjesus.com

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在數據傳輸過程中,json是以文本,即字元串的形式傳遞的,而JS操作的是JSON對象,所以,JSON對象和JSON字元串之間的相互轉換是關鍵。例如:JSON字元串:var str1 = '{ "name": "cxh", "sex": "man" }'; JSON對象:var str2 = { "n ...
  • 上大學學習軟體設計有一年多了,明年五月就要畢業了。回頭看看發現自己其實挺差勁的,不能因為在一群不學習的人中就覺得自己多厲害。其實自己也是個廢物呢:) 最近開通了博客所以就整理了一下筆記,在這裡發佈一下自己以前學習css時總是記不住去翻書又很常用的屬性,都是一些很基礎的,大神輕噴。很適合初學者多看看。 ...
  • html部分(圖片都是本地,自己需要改動圖片) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="css/one.css" ...
  • https://github.com/Trinea/android-open-project ...
  • 以上就介紹了比SwipeRefreshLayout更漂亮和強大的下拉刷新控制項:Android-MaterialRefreshLayout 1.xml 2.Java 3、參考網站 https://github.com/android-cjj/Android-MaterialRefreshLayout/ ...
  • SQL 對大小寫不敏感! 數據操作語言 (DML): select - 從資料庫表中獲取數據 update - 更新資料庫表中的數據 delete - 從資料庫表中刪除數據 insert into - 向資料庫表中插入數據 數據定義語言 (DDL): create database - 創建新資料庫 ...
  • 公司的redis業務很多,redis監控自然也是DB監控的一大模塊,包括採集、展示、監控告警。本文主要介紹redis監控的主要指標和採集方法。 一、Redis監控系統邏輯 1、DBA通過前臺頁面添加redis監控,填寫ip和埠,配置閾值、負責人等信息 2、前臺調用自動調度平臺介面將redis監控採 ...
  • ImageSharp 是支持.NET Core跨平臺圖形處理庫,ImageSharp是ImageProcessor 的.NET Core跨平臺實現。 ImageSharp 支持如下操作: 調整大小,裁剪,翻轉,旋轉,邊緣檢測等。 支持BMP,PNG,GIF,JPEG 編碼器。 EXIF 讀取和針對J ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...