Merge pull request #113 from gitter-badger/gitter-badge
[sddekit.git] / src / sd_util.c
blobc6d33a714541fb169b7c3b628fdce316b9ac6548
1 /* copyright 2016 Apache 2 sddekit authors */
3 #include "sddekit.h"
5 static int compare_int(const void *a, const void *b)
7 if ( *(uint32_t*) a < *(uint32_t*) b ) return -1;
8 if ( *(uint32_t*) a == *(uint32_t*) b ) return 0;
9 else /* a > b */ return 1;
12 sd_stat sd_util_uniqi(
13 uint32_t n,
14 uint32_t * restrict ints,
15 uint32_t * restrict nuniq,
16 uint32_t ** uints)
18 uint32_t i, j, *ints_copy;
20 if (n==0) return SD_OK;
22 if (n==1) {
23 *nuniq = 1;
24 if ((*uints = sd_malloc (sizeof(uint32_t)))==NULL) {
25 sd_err("failed to allocate memory for unique integers");
26 return SD_ERR;
28 (*uints)[0] = ints[0];
29 return SD_OK;
32 /* sort copy of input vector */
33 if ((ints_copy = sd_malloc(sizeof(uint32_t) * n))==NULL) {
34 sd_err("failed to allocate memory for ints copy.");
35 return SD_ERR;
37 memcpy(ints_copy, ints, n*sizeof(uint32_t));
39 qsort(ints_copy, n, sizeof(uint32_t), compare_int);
41 /* count uniq */
42 *nuniq = 1;
43 for (i=0; i<(n-1); i++)
44 if (ints_copy[i] != ints_copy[i+1])
45 (*nuniq)++;
47 if ((*uints = sd_malloc (sizeof(uint32_t) * *nuniq))==NULL) {
48 sd_err("failed to allocate memory for unique integers.");
49 sd_free(ints_copy);
50 return SD_ERR;
53 /* copy unique into output array */
54 j = 0;
55 (*uints)[j++] = ints_copy[0];
56 for (i=0; i<(n-1); i++)
57 if (ints_copy[i] != ints_copy[i+1])
58 (*uints)[j++] = ints_copy[i+1];
60 sd_free(ints_copy);
62 return SD_OK;
65 sd_stat sd_util_read_square_matrix(const char *fname, uint32_t *n, double **w)
67 uint32_t nn;
68 FILE *fd;
69 double _, *wi;
70 /* open file */
71 fd = fopen(fname, "r");
72 if (fd==NULL) {
73 sd_err("failed to open file");
74 return SD_ERR;
76 /* count number of readable elements */
77 nn = 0;
79 int count;
80 while (1) {
81 count = fscanf(fd, "%lg", &_);
82 if (count < 1)
83 break;
84 nn++;
87 rewind(fd);
88 /* setup memory */
89 *n = (uint32_t) sqrt(nn);
90 wi = sd_malloc (sizeof(double)*nn);
91 *w = wi;
92 if (wi==NULL) {
93 fclose(fd);
94 return SD_ERR;
96 /* read data into memory this time */
98 int count;
99 while (1) {
100 count = fscanf(fd, "%lg", wi++);
101 if (count < 1)
102 break;
105 fclose(fd);
106 return SD_OK;