-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsledger-sort.c
More file actions
94 lines (75 loc) · 1.74 KB
/
Copy pathsledger-sort.c
File metadata and controls
94 lines (75 loc) · 1.74 KB
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
87
88
89
90
91
92
93
94
#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#define STB_DS_IMPLEMENTATION
#include "stb_ds.h"
#include "sledger.h"
struct posting *sorted_postings;
int factor = 1;
int flowcmp(const struct posting *a, const struct posting *b) {
struct decimal da = {}, db = {};
struct decimal temp;
for (int i = 0; i < arrlen(a->lines); i++) {
decimal_abs(&a->lines[i].val, &temp);
decimal_add(&da, &temp, &da);
}
for (int i = 0; i < arrlen(b->lines); i++) {
decimal_abs(&b->lines[i].val, &temp);
decimal_add(&db, &temp, &db);
}
int ret = decimal_cmp(&da, &db);
if (ret == -2) {
fprintf(stderr, "decimal_cmp: failure\n");
exit(1);
}
return ret;
}
int (*cmp)(const struct posting *a, const struct posting *b) = NULL;
void sort_processor(struct posting *posting, void *data) {
int left = 0;
int right = arrlen(sorted_postings) - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (factor * cmp(posting, &sorted_postings[mid]) < 0) {
right = mid - 1;
} else {
left = mid + 1;
}
}
arrins(sorted_postings, left, (struct posting){});
assert(posting_dup(sorted_postings + left, posting) >= 0);
}
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "dfi")) != -1) {
switch (opt) {
case 'i':
factor = -1;
break;
case 'd':
cmp = tmcmp;
break;
case 'f':
cmp = flowcmp;
break;
default:
}
}
if (cmp == NULL)
return 1;
if (process_postings(sort_processor, NULL) == -1) {
return 1;
}
for (int i = 0; i < arrlen(sorted_postings); i++) {
struct posting *posting = sorted_postings + i;
print_posting(posting);
}
return 0;
}