aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-05-03 18:33:56 +0200
committerAbigail <abigail@abigail.be>2021-05-03 18:33:56 +0200
commit2d04791820175079daea868135ea04cf7cc5be0c (patch)
tree06ed2597fbffd9f1e8bee475cb561ac5db9fe477
parent2a9661ee4386ae9a9e7caa8a0dcee83ce94b40fd (diff)
downloadperlweeklychallenge-club-2d04791820175079daea868135ea04cf7cc5be0c.tar.gz
perlweeklychallenge-club-2d04791820175079daea868135ea04cf7cc5be0c.tar.bz2
perlweeklychallenge-club-2d04791820175079daea868135ea04cf7cc5be0c.zip
C solution for week 111, part 2
-rw-r--r--challenge-111/abigail/README.md1
-rw-r--r--challenge-111/abigail/c/ch-2.c60
2 files changed, 61 insertions, 0 deletions
diff --git a/challenge-111/abigail/README.md b/challenge-111/abigail/README.md
index 53215ce77d..3f7fc99b5f 100644
--- a/challenge-111/abigail/README.md
+++ b/challenge-111/abigail/README.md
@@ -51,6 +51,7 @@ to standard output. In case of ties, we print the first one found.
### Solutions
* [GNU AWK](awk/ch-2.gawk)
+* [C](c/ch-2.c)
* [Perl](perl/ch-2.pl)
### Blog
diff --git a/challenge-111/abigail/c/ch-2.c b/challenge-111/abigail/c/ch-2.c
new file mode 100644
index 0000000000..a677e4cad6
--- /dev/null
+++ b/challenge-111/abigail/c/ch-2.c
@@ -0,0 +1,60 @@
+# include <stdlib.h>
+# include <stdio.h>
+# include <string.h>
+# include <stdbool.h>
+# include <ctype.h>
+
+/*
+ * See ../README.md
+ */
+
+/*
+ * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o < input-file
+ */
+
+int main (void) {
+ char * line = NULL;
+ size_t len = 0;
+ char * longest = NULL;
+ size_t longest_size = 0;
+
+ while (getline (&line, &len, stdin) != -1) {
+ /*
+ * First check whether the word has its characters
+ * in lexical order.
+ */
+ size_t i = 0;
+ bool in_order = 1;
+ while (line [i] != '\n') {
+ if ((i && tolower (line [i]) < tolower (line [i - 1])) ||
+ !isalpha (line [i])) {
+ in_order = false;
+ break;
+ }
+ i ++;
+ }
+
+ /*
+ * If we have a word with its characters in lexical order, and
+ * it's longer than the longest word found, keep the word.
+ */
+ if (in_order && i > longest_size) {
+ longest_size = i;
+ if ((longest = (char *) realloc (longest, (i + 1) * sizeof (char)))
+ == NULL) {
+ perror ("Realloc failed");
+ exit (1);
+ }
+ for (size_t j = 0; j <= i; j ++) { /* Copies the newline as well */
+ longest [j] = line [j];
+ }
+ longest [i + 1] = '\0';
+ }
+ }
+ printf ("%s", longest);
+
+ free (line);
+ free (longest);
+
+ return (0);
+}