我試圖找出如何根據陣列中最常見的數字計算“權重選擇”,以供 AI 選擇特定數字。
例如,我有一個函式可以計算陣列中最常見的數字,并允許 AI 選擇一個特定的選項來讓玩家輸。
就目前而言,如果最常見的數字是 1,那么將有 50% 的機會選擇 2。理想情況下,如果陣列充滿 1,它應該只有 50% 的機會發生。
有沒有人對此有任何解決方案?我一直沒能解決。感謝幫助。
PS:我知道這個函式可能寫得很糟糕,只是想得到一個原型/骨架函式。
uj5u.com熱心網友回復:
這看起來是一個完美的地方std::discrete_distribution。
演練:
#include <algorithm>
#include <iostream>
#include <map>
#include <random>
#include <vector>
// A seeded pseudo random number generator:
static std::mt19937 gen(std::random_device{}());
int main() {
假設您在vector. 您似乎將它們放在一個陣列中,但我會使用 avector因為它更容易處理。
// filled with some example choices:
std::vector<int> m_playerChoices{10,10,11,10,22,22,10};
我首先制作一個直方圖,以便您計算每個選擇的數量:
std::map<int, int> hist;
for(int choice : m_playerChoices) {
hist[choice];
}
然后我們從直方圖中提取選項和計數,并放入兩個單獨vector的 s。一個包含所有唯一選項,一個對應的包含每個選項的計數,稱為weights.
std::vector<int> unique_choices;
std::vector<int> weights;
for(auto[choice, count] : hist) {
unique_choices.push_back(choice);
weights.push_back(count);
}
然后weights用于創建discrete_distribution:
std::discrete_distribution<int> dist(weights.begin(), weights.end());
您現在可以呼叫偽亂數生成器并使用此離散分布來獲取唯一數字之一,并且每個數字的概率將完全根據您開始使用的每個選擇的計數:
for(int i = 0; i < 100; i) {
std::cout << unique_choices[dist(gen)] << '\n';
}
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/495357.html
