commit 4e525f0ca71f7536e09605ac616c3f2b76b12c9b
Author: zerous Naveen Narayanan <zerous@nocebo.space>
Date: Sun, 3 Mar 2019 20:42:58 +0100
Initial commit
Diffstat:
A | res.c | | | 131 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 131 insertions(+), 0 deletions(-)
diff --git a/res.c b/res.c
@@ -0,0 +1,131 @@
+#include <error.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+void delstr(char *);
+void store(char);
+void strstore(char *);
+void isort(void **, int (*)(const void *, const void *));
+
+char *buf;
+char *end;
+char *nextelem;
+char **strbuf;
+char **strnextelem;
+char **strend;
+unsigned long nstr;
+
+int
+comp(const void *a, const void *b)
+{
+ char *k = (char *)a;
+ char *j = (char *)b;
+
+ return *k - *j;
+}
+
+
+int
+main(int argc, char **argv)
+{
+ char c;
+
+ while ((c = getc(stdin)) != EOF) {
+ store(c);
+ }
+ printf("nstr: %lu\n", nstr);
+ /* qsort(strbuf, nstr, sizeof(char *), comp); */
+ isort((void **)strbuf, comp);
+
+ for (int i = 0; i < nstr; i++)
+ printf("%s\n", strbuf[i]);
+
+ free(strbuf);
+ free(buf);
+
+ return 0;
+}
+
+void
+store(char c)
+{
+ static int growthfact = 1;
+ char *t;
+
+ if (nextelem == end) {
+ if ((t = realloc(buf, growthfact * 512 * sizeof(char))) == NULL)
+ error(1, 1, "realloc");
+ nextelem = t + (nextelem - buf);
+ buf = t;
+ end = buf + (growthfact * 512);
+ growthfact++;
+ }
+
+ if (nextelem != end) {
+ if (nextelem == buf) { /* first time */
+ strstore(nextelem);
+ *nextelem++ = c;
+ }
+
+ if (c == '\n') {
+ *nextelem++ = '\0';
+ strstore(nextelem);
+ }
+ else {
+ *nextelem++ = c;
+ }
+ }
+}
+
+void
+strstore(char *s)
+{
+ static int growthfact = 1;
+ char **t;
+
+ if (strnextelem == strend) {
+ if ((t = realloc(strbuf, growthfact * 512 * sizeof(char *))) == NULL)
+ error(1, 1, "realloc");
+ strnextelem = t + (strnextelem - strbuf);
+ strbuf = t;
+ strend = strbuf + (growthfact * 512);
+ growthfact++;
+ }
+
+ if (strnextelem != strend) {
+ *strnextelem++ = s;
+ nstr++;
+ }
+}
+
+void
+delstr(char *s)
+{
+ for (int i = 0; i < nstr; i++) {
+ if (strcmp(strbuf[i],s) == 0) {
+ memmove(strbuf + i, strbuf + i + 1,
+ (nstr - i - 1) * sizeof(char *));
+ nstr--;
+ return;
+ }
+ }
+}
+
+void
+isort(void **ar, int (*cmp)(const void *a, const void *b))
+{
+ int j;
+
+ for (int i = 1; i < nstr; i++) {
+ printf("%d\n", i);
+ j = i - 1;
+ void *val = ar[i];
+ while (j >= 0 && cmp(ar[j], val) > 0) {
+ ar[j + 1] = ar[j];
+ j--;
+ }
+ ar[j+1] = val;
+ }
+}
+