| 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 |
#include <stdio.h> |
| 28 |
#include <stdlib.h> |
| 29 |
#include <math.h> |
| 30 |
#include <string.h> |
| 31 |
#include <assert.h> |
| 32 |
#include "dist.h" |
| 33 |
|
| 34 |
extern void error(const char *format, ...); |
| 35 |
|
| 36 |
struct _dist_t |
| 37 |
{ |
| 38 |
uint64_t *bins, nvalues; |
| 39 |
int nbins; |
| 40 |
int npow; |
| 41 |
int nexact; |
| 42 |
int nlevel; |
| 43 |
}; |
| 44 |
|
| 45 |
dist_t *dist_init(int npow) |
| 46 |
{ |
| 47 |
dist_t *dist = (dist_t*) calloc(1,sizeof(dist_t)); |
| 48 |
dist->npow = npow; |
| 49 |
dist->nexact = pow(10,npow); |
| 50 |
dist->nlevel = dist->nexact - pow(10,npow-1); |
| 51 |
return dist; |
| 52 |
} |
| 53 |
|
| 54 |
void dist_destroy(dist_t *dist) |
| 55 |
{ |
| 56 |
if ( !dist ) return; |
| 57 |
free(dist->bins); |
| 58 |
free(dist); |
| 59 |
} |
| 60 |
|
| 61 |
int dist_nbins(dist_t *dist) |
| 62 |
{ |
| 63 |
return dist->nbins; |
| 64 |
} |
| 65 |
|
| 66 |
int dist_nvalues(dist_t *dist) |
| 67 |
{ |
| 68 |
return dist->nvalues; |
| 69 |
} |
| 70 |
|
| 71 |
uint32_t dist_insert(dist_t *dist, uint32_t value) |
| 72 |
{ |
| 73 |
int ibin; |
| 74 |
|
| 75 |
if ( value <= dist->nexact ) |
| 76 |
ibin = value; |
| 77 |
else |
| 78 |
{ |
| 79 |
int npow = (int) log10(value); |
| 80 |
int level = npow - dist->npow + 1; |
| 81 |
uint32_t step = pow(10, level); |
| 82 |
ibin = dist->nexact + dist->nlevel*(level-1) + (value - pow(10,npow)) / step; |
| 83 |
} |
| 84 |
|
| 85 |
if ( ibin >= dist->nbins ) |
| 86 |
{ |
| 87 |
dist->bins = (uint64_t*) realloc(dist->bins, sizeof(*dist->bins)*(ibin+1)); |
| 88 |
memset(dist->bins + dist->nbins, 0, (ibin+1 - dist->nbins)*sizeof(*dist->bins)); |
| 89 |
dist->nbins = ibin+1; |
| 90 |
} |
| 91 |
dist->bins[ibin]++; |
| 92 |
dist->nvalues++; |
| 93 |
return ibin; |
| 94 |
} |
| 95 |
uint32_t dist_insert_n(dist_t *dist, uint32_t value, uint32_t cnt) |
| 96 |
{ |
| 97 |
if ( !cnt ) return 0; |
| 98 |
int ibin = dist_insert(dist, value); |
| 99 |
dist->bins[ibin] += cnt - 1; |
| 100 |
dist->nvalues += cnt; |
| 101 |
return ibin; |
| 102 |
} |
| 103 |
|
| 104 |
uint64_t dist_get(dist_t *dist, uint32_t idx, uint32_t *beg, uint32_t *end) |
| 105 |
{ |
| 106 |
if ( idx < dist->nexact ) |
| 107 |
{ |
| 108 |
if ( beg ) *beg = idx; |
| 109 |
if ( end ) *end = idx + 1; |
| 110 |
} |
| 111 |
else |
| 112 |
{ |
| 113 |
int level = (idx - dist->nexact) / dist->nlevel + 1; |
| 114 |
int bin = idx - dist->nexact - dist->nlevel*(level-1); |
| 115 |
|
| 116 |
uint32_t step = pow(10, level); |
| 117 |
uint32_t value = pow(10, level + dist->npow - 1) + step*bin; |
| 118 |
|
| 119 |
if ( beg ) *beg = value; |
| 120 |
if ( end ) *end = value + step; |
| 121 |
} |
| 122 |
return dist->bins[idx]; |
| 123 |
} |
| 124 |
|