Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / include / Distribution.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- 
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software 
11  * Foundation.  See file COPYING.
12  * 
13  */
14
15
16 #ifndef CEPH_DISTRIBUTION_H
17 #define CEPH_DISTRIBUTION_H
18
19 #include <vector>
20 using namespace std;
21
22 class Distribution {
23   vector<float> p;
24   vector<int> v;
25
26  public:
27   //Distribution() { 
28   //}
29   
30   unsigned get_width() {
31     return p.size();
32   }
33
34   void clear() {
35     p.clear();
36     v.clear();
37   }
38   void add(int val, float pr) {
39     p.push_back(pr);
40     v.push_back(val);
41   }
42
43   void random() {
44     float sum = 0.0;
45     for (unsigned i=0; i<p.size(); i++) {
46       p[i] = (float)(rand() % 10000);
47       sum += p[i];
48     }
49     for (unsigned i=0; i<p.size(); i++) 
50       p[i] /= sum;
51   }
52
53   int sample() {
54     float s = (float)(rand() % 10000) / 10000.0;
55     for (unsigned i=0; i<p.size(); i++) {
56       if (s < p[i]) return v[i];
57       s -= p[i];
58     }
59     ceph_abort();
60     return v[p.size() - 1];  // hmm.  :/
61   }
62
63   float normalize() {
64     float s = 0.0;
65     for (unsigned i=0; i<p.size(); i++)
66       s += p[i];
67     for (unsigned i=0; i<p.size(); i++)
68       p[i] /= s;
69     return s;
70   }
71
72 };
73
74 #endif