1 | #define __MODUL__ |
---|
2 | #include "spreadin.h" |
---|
3 | #include <stdlib.h> |
---|
4 | |
---|
5 | /* -------------------------------------------------------------------------- */ |
---|
6 | /* Spreading newSpreading(double *value, int values) */ |
---|
7 | /* ------------------------------------------------------ 20.05.95 16:42 ---- */ |
---|
8 | Spreading newSpreading(double *value, int values) |
---|
9 | { |
---|
10 | Spreading s; |
---|
11 | int v; |
---|
12 | double val = 0.0, |
---|
13 | sum = 0.0; |
---|
14 | |
---|
15 | s = malloc(sizeof(struct S_Spreading)); |
---|
16 | if (!s) outOfMemory(); |
---|
17 | |
---|
18 | assert(values>0); |
---|
19 | |
---|
20 | s->values = values; |
---|
21 | s->border = malloc(sizeof(*(s->border))*values); |
---|
22 | if (!s->border) outOfMemory(); |
---|
23 | |
---|
24 | for (v = 0; v<values; v++) sum += value[v]; /* Summe bilden */ |
---|
25 | |
---|
26 | for (v = 0; v<values; v++) |
---|
27 | { |
---|
28 | val += value[v]; |
---|
29 | s->border[v] = (val/sum)*RAND_MAX; |
---|
30 | } |
---|
31 | |
---|
32 | s->border[values-1] = RAND_MAX; |
---|
33 | |
---|
34 | /* for (v = 0; v<values; v++) printf("%f -> %i\n", value[v], s->border[v]); */ |
---|
35 | /* printf("---\n"); */ |
---|
36 | |
---|
37 | return s; |
---|
38 | } |
---|
39 | /* -------------------------------------------------------------------------- */ |
---|
40 | /* void freeSpreading(Spreading s) */ |
---|
41 | /* ------------------------------------------------------ 20.05.95 16:42 ---- */ |
---|
42 | void freeSpreading(Spreading s) |
---|
43 | { |
---|
44 | free(s->border); |
---|
45 | free(s); |
---|
46 | } |
---|
47 | /* -------------------------------------------------------------------------- */ |
---|
48 | /* int spreadRand(Spreading s) */ |
---|
49 | /* ------------------------------------------------------ 20.05.95 16:42 ---- */ |
---|
50 | int spreadRand(Spreading s) |
---|
51 | { |
---|
52 | int val = rand(), |
---|
53 | l = 0, |
---|
54 | h = s->values-1, |
---|
55 | m; |
---|
56 | |
---|
57 | while (1) |
---|
58 | { |
---|
59 | m = (l+h)/2; |
---|
60 | |
---|
61 | if (val<=s->border[m]) |
---|
62 | { |
---|
63 | if (m==0 || val>s->border[m-1]) break; |
---|
64 | h = m; |
---|
65 | } |
---|
66 | else |
---|
67 | { |
---|
68 | if (m==(h-1)) |
---|
69 | { |
---|
70 | if (val<=s->border[h]) |
---|
71 | { |
---|
72 | m = h; |
---|
73 | break; |
---|
74 | } |
---|
75 | } |
---|
76 | |
---|
77 | l = m; |
---|
78 | } |
---|
79 | } |
---|
80 | |
---|
81 | assert(m>=0 && m<s->values); |
---|
82 | assert(val<=s->border[m]); |
---|
83 | assert(m==0 || val>=s->border[m-1]); |
---|
84 | |
---|
85 | return m; |
---|
86 | } |
---|
87 | |
---|
88 | |
---|