Last change
on this file was
16766,
checked in by westram, 7 years ago
|
|
-
Property svn:eol-style set to
native
-
Property svn:keywords set to
Author Date Id Revision
|
File size:
1.3 KB
|
Line | |
---|
1 | #define __MODUL__ |
---|
2 | #include "spreadin.h" |
---|
3 | #include <stdlib.h> |
---|
4 | |
---|
5 | Spreading newSpreading(double *value, int values) { |
---|
6 | Spreading s; |
---|
7 | int v; |
---|
8 | double val = 0.0, |
---|
9 | sum = 0.0; |
---|
10 | |
---|
11 | s = malloc(sizeof(struct S_Spreading)); |
---|
12 | if (!s) outOfMemory(); |
---|
13 | |
---|
14 | assert(values>0); |
---|
15 | |
---|
16 | s->values = values; |
---|
17 | s->border = malloc(sizeof(*(s->border))*values); |
---|
18 | if (!s->border) outOfMemory(); |
---|
19 | |
---|
20 | for (v = 0; v<values; v++) sum += value[v]; // Summe bilden |
---|
21 | |
---|
22 | for (v = 0; v<values; v++) { |
---|
23 | val += value[v]; |
---|
24 | s->border[v] = (val/sum)*RAND_MAX; |
---|
25 | } |
---|
26 | |
---|
27 | s->border[values-1] = RAND_MAX; |
---|
28 | |
---|
29 | return s; |
---|
30 | } |
---|
31 | void freeSpreading(Spreading s) { |
---|
32 | free(s->border); |
---|
33 | free(s); |
---|
34 | } |
---|
35 | int spreadRand(Spreading s) { |
---|
36 | int val = rand(), |
---|
37 | l = 0, |
---|
38 | h = s->values-1, |
---|
39 | m; |
---|
40 | |
---|
41 | while (1) { |
---|
42 | m = (l+h)/2; |
---|
43 | |
---|
44 | if (val<=s->border[m]) { |
---|
45 | if (m==0 || val>s->border[m-1]) break; |
---|
46 | h = m; |
---|
47 | } |
---|
48 | else { |
---|
49 | if (m==(h-1)) { |
---|
50 | if (val<=s->border[h]) { |
---|
51 | m = h; |
---|
52 | break; |
---|
53 | } |
---|
54 | } |
---|
55 | |
---|
56 | l = m; |
---|
57 | } |
---|
58 | } |
---|
59 | |
---|
60 | assert(m>=0 && m<s->values); |
---|
61 | assert(val<=s->border[m]); |
---|
62 | assert(m==0 || val>=s->border[m-1]); |
---|
63 | |
---|
64 | return m; |
---|
65 | } |
---|
66 | |
---|
67 | |
---|
Note: See
TracBrowser
for help on using the repository browser.