zoukankan      html  css  js  c++  java
  • Shuffle an Array (水塘抽样)

    随机性问题

    水塘抽样算法可保证每个样本被抽到的概率相等

    使用场景:从包含n个项目的集合S中选取k个样本,其中n为一很大或未知的数量,尤其适用于不能把所有n个项目都存放到主内存的情况

    Knuth洗牌算法

    拿起第i张牌时,只从它前面的牌随机选出j,或从它后面的牌随机选出j交换即可

     1 class Solution {
     2 public:
     3     Solution(vector<int>& nums) {
     4         v = nums;
     5     }
     6     
     7     /** Resets the array to its original configuration and return it. */
     8     vector<int> reset() {
     9         return v;
    10     }
    11     
    12     /** Returns a random shuffling of the array. */
    13     vector<int> shuffle() {
    14         vector<int> res = v;
    15         for (int i = 0; i < res.size(); ++i) {
    16             int t = i + rand() % (res.size() - i);
    17             swap(res[i], res[t]);
    18         }
    19         return res;
    20     }
    21     vector<int> v;
    22 };
    23 
    24 /**
    25  * Your Solution object will be instantiated and called as such:
    26  * Solution* obj = new Solution(nums);
    27  * vector<int> param_1 = obj->reset();
    28  * vector<int> param_2 = obj->shuffle();
    29  */
  • 相关阅读:
    JZOJ5809 数羊
    P3313 [SDOI2014]旅行
    2019.10.22 NOIP模拟测试 day2
    P4322 [JSOI2016]最佳团体
    P1850 换教室
    P3225 [HNOI2012]矿场搭建
    P2607 [ZJOI2008]骑士
    2019.10.21 NOIP模拟测试 day1
    AFO
    禁止加载浏览器图片
  • 原文地址:https://www.cnblogs.com/demian/p/11240184.html
Copyright © 2011-2022 走看看