Probdist: Make items[] contain the sums instead of individual probabilities
[pachi.git] / probdist.c
blob3d04ff484fb2988e0426ce410cc946829957dd40
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
6 #include "move.h"
7 #include "probdist.h"
8 #include "random.h"
10 struct probdist *
11 probdist_init(struct probdist *pd, int n)
13 if (!pd) pd = malloc(sizeof(*pd));
14 pd->n = n;
15 pd->items = calloc(n, sizeof(pd->items[0]));
16 pd->items[0] = 0; // probdist_set() requires [0] to be initialized
17 return pd;
20 int
21 probdist_pick(struct probdist *pd)
23 assert(pd->items[pd->n - 1] >= 0);
24 /* TODO: float random */
25 float stab = (float) fast_random(65536) / 65536 * pd->items[pd->n - 1];
26 //fprintf(stderr, "stab %f / %f\n", stab, pd->items[pd->n - 1]);
27 for (int i = 0; i < pd->n; i++) {
28 if (stab <= pd->items[i])
29 return i;
31 //fprintf(stderr, "overstab %f (total %f, sum %f)\n", stab, pd->items[pd->n - 1], sum);
32 assert(0);
33 return -1;
36 void
37 probdist_done(struct probdist *pd) {
38 free(pd->items);