Merge branch 'master' of ssh://repo.or.cz/srv/git/pachi
[pachi/pachi-r6144.git] / probdist.c
blobbd932ab7badd8dc90781a83d7ea852ca1b772d0e
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
6 //#define DEBUG
7 #include "debug.h"
8 #include "move.h"
9 #include "probdist.h"
10 #include "random.h"
11 #include "board.h"
13 coord_t
14 probdist_pick(struct probdist *pd, coord_t *ignore)
16 double total = probdist_total(pd) - PROBDIST_EPSILON;
17 assert(total >= 0);
18 double stab = fast_frandom() * total;
19 if (DEBUGL(6))
20 fprintf(stderr, "stab %f / %f\n", stab, total);
22 int r = 0;
23 while (stab > pd->rowtotals[r] + PROBDIST_EPSILON) {
24 stab -= pd->rowtotals[r];
25 r++;
26 assert(r < board_size(pd->b));
28 for (coord_t c = r * board_size(pd->b); c < board_size2(pd->b); c++) {
29 if (DEBUGL(6))
30 fprintf(stderr, "[%s] %f (%f)\n", coord2sstr(c, pd->b), pd->items[c], stab);
31 if (c == *ignore) {
32 ignore++;
33 continue;
35 if (stab <= pd->items[c])
36 return c;
37 stab -= pd->items[c];
40 fprintf(stderr, "overstab %f (total %f)\n", stab, total);
41 assert(0);
42 return -1;