2

## 【c/c++學習筆記】利用rand()產生隨機數，教你模擬不公平的骰子

`rand()`的效果可以產生從`0`~`RAND_MAX`(int的最大值)之間的隨機整數，

``````#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {
for(int i = 0 ; i < 10 ;i++){
cout << rand() << endl;
}
return 0;
}
``````

``````1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421
``````

# 每次執行程式的結果都一樣?

(參考資料: C/C++ 使用 rand 函數產生隨機亂數教學與範例程式碼)

``````#include <iostream>
#include <cstdlib> /* 亂數相關函數 */
#include <ctime>   /* 時間相關函數 */
using namespace std;

int main() {
srand( time(NULL));
for(int i = 0 ; i < 10 ;i++){
cout << rand() << endl;
}
return 0;
}
``````

## 0~1之間的隨機浮點數

`double x = (double) rand() / (RAND_MAX + 1.0);`

## a~b之間的隨機浮點數

`double x = (b - a) * rand() / (RAND_MAX + 1.0) + a;`

## a~b之間的隨機整數

`int x = rand() % (b - a + 1) + a;`

(多個隨機數的情形再自行類推)

# c++ 程式: 584ms, AC

``````class Solution {
public:
vector<int> accu_prob;
Solution(vector<int>& w){
accu_prob.resize(w.size());
accu_prob[0]= w[0];
for(int i=1 ;i<w.size();i++){
accu_prob[i]= accu_prob[i-1]+w[i];
}
}

int pickIndex() {
int R = rand() % accu_prob.back();
for(int i =0 ; i<accu_prob.size();i++){
if(R<accu_prob[i]){
return i;
}
}
return accu_prob.size()-1;
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
``````

# c++ 程式(二分查找): 180ms, AC

``````class Solution {
//函數功能: 回傳在排序陣列中，第一個大於目標值的位置
int firstGreaterEqual(vector<int>& nums, int target) {
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target)
left = mid + 1;
else
right = mid;
}
return right;
}
public:
vector<int> accu_prob;
Solution(vector<int>& w){
accu_prob.resize(w.size());
accu_prob[0]= w[0];
for(int i=1 ;i<w.size();i++){
accu_prob[i]= accu_prob[i-1]+w[i];
}
}

int pickIndex() {
int R = rand() % accu_prob.back();
return firstGreaterEqual(accu_prob, R);
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
``````