aboutsummaryrefslogtreecommitdiff
path: root/km-rand.c
blob: 1410861aa857e52c04a010c19280f3f8077bb2b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdbool.h>
#include "util.h"
#include "km.h"

// fill buffer with N random floats
bool
km_rand_fill(
  km_rand_t * const rs,
  const size_t num_floats,
  float * const floats
) {
  return rs->cbs->fill(rs, num_floats, floats);
}

// fill buffer with N random size_ts
bool
km_rand_fill_sizes(
  km_rand_t * const rs,
  const size_t num_sizes,
  size_t * const sizes
) {
  return rs->cbs->fill_sizes(rs, num_sizes, sizes);
}

// finalize random source
void
km_rand_fini(
  km_rand_t * const rs
) {
  if (rs->cbs->fini) {
    rs->cbs->fini(rs);
  }
}

// fill callback for system random source
static bool
system_on_fill(
  km_rand_t * const rs,
  const size_t num_floats,
  float * const floats
) {
  UNUSED(rs);

  // generate random cluster centers
  for (size_t i = 0; i < num_floats; i++) {
    floats[i] = 1.0 * rand() / RAND_MAX;
  }

  // return success
  return true;
}

// fill sizes callback for system random source
static bool
system_on_fill_sizes(
  km_rand_t * const rs,
  const size_t num_sizes,
  size_t * const sizes
) {
  UNUSED(rs);

  // generate random size_ts
  for (size_t i = 0; i < num_sizes; i++) {
    sizes[i] = rand();
  }

  // return success
  return true;
}

// system random source callbacks
static const km_rand_cbs_t
SYSTEM_CBS = {
  .fill       = system_on_fill,
  .fill_sizes = system_on_fill_sizes,
  .fini       = NULL,
};

// init system random source (uses system rand())
void
km_rand_init_system(
  km_rand_t * const rs
) {
  rs->cbs = &SYSTEM_CBS;
  rs->data = NULL;
}