]> git.proxmox.com Git - ceph.git/blob - ceph/src/include/Distribution.h
import quincy beta 17.1.0
[ceph.git] / 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
21 class Distribution {
22 std::vector<float> p;
23 std::vector<int> v;
24
25 public:
26 //Distribution() {
27 //}
28
29 unsigned get_width() {
30 return p.size();
31 }
32
33 void clear() {
34 p.clear();
35 v.clear();
36 }
37 void add(int val, float pr) {
38 p.push_back(pr);
39 v.push_back(val);
40 }
41
42 void random() {
43 float sum = 0.0;
44 for (unsigned i=0; i<p.size(); i++) {
45 p[i] = (float)(rand() % 10000);
46 sum += p[i];
47 }
48 for (unsigned i=0; i<p.size(); i++)
49 p[i] /= sum;
50 }
51
52 int sample() {
53 float s = (float)(rand() % 10000) / 10000.0;
54 for (unsigned i=0; i<p.size(); i++) {
55 if (s < p[i]) return v[i];
56 s -= p[i];
57 }
58 ceph_abort();
59 return v[p.size() - 1]; // hmm. :/
60 }
61
62 float normalize() {
63 float s = 0.0;
64 for (unsigned i=0; i<p.size(); i++)
65 s += p[i];
66 for (unsigned i=0; i<p.size(); i++)
67 p[i] /= s;
68 return s;
69 }
70
71 };
72
73 #endif