aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/abigail/c
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-05-31 20:16:50 +0200
committerAbigail <abigail@abigail.be>2021-06-01 15:38:19 +0200
commit4f04dab2323d4219a5eb906c4bbc28059fecb10c (patch)
tree17249389d57132215ed5cb3c77b3b7e8a72cb156 /challenge-115/abigail/c
parent9def9e9e8ab96a506f322adf88fbdb182fd9acb7 (diff)
downloadperlweeklychallenge-club-4f04dab2323d4219a5eb906c4bbc28059fecb10c.tar.gz
perlweeklychallenge-club-4f04dab2323d4219a5eb906c4bbc28059fecb10c.tar.bz2
perlweeklychallenge-club-4f04dab2323d4219a5eb906c4bbc28059fecb10c.zip
AWK, Bash, C, Lua, Node.js, Perl, Python and Ruby solutions for week 115, part 2
Diffstat (limited to 'challenge-115/abigail/c')
-rw-r--r--challenge-115/abigail/c/ch-2.c71
1 files changed, 71 insertions, 0 deletions
diff --git a/challenge-115/abigail/c/ch-2.c b/challenge-115/abigail/c/ch-2.c
new file mode 100644
index 0000000000..975aace0ef
--- /dev/null
+++ b/challenge-115/abigail/c/ch-2.c
@@ -0,0 +1,71 @@
+# include <stdlib.h>
+# include <stdio.h>
+# include <string.h>
+# include <ctype.h>
+
+/*
+ * See ../README.md
+ */
+
+/*
+ * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o < input-file
+ */
+
+# define NR_OF_DIGITS 10
+# define ZERO '0'
+
+int main (void) {
+ char * line = NULL;
+ size_t len = 0;
+ size_t str_len;
+
+ while ((str_len = getline (&line, &len, stdin)) != -1) {
+ /*
+ * Read in a line of data. Count the number of digits,
+ * and put them in an array 'digits'.
+ */
+ char * line_ptr = line;
+ int digits [NR_OF_DIGITS];
+ for (size_t i = 0; i < NR_OF_DIGITS; i ++) {
+ digits [i] = 0;
+ }
+ while (* line_ptr) {
+ if (isdigit (* line_ptr)) {
+ digits [* line_ptr - ZERO] ++;
+ }
+ line_ptr ++;
+ }
+
+ /*
+ * Find the lowest even digit.
+ */
+ int last = -1;
+ for (ssize_t i = NR_OF_DIGITS - 2; i >= 0; i -= 2) {
+ if (digits [i]) {
+ last = i;
+ }
+ }
+
+ /*
+ * Skip if the input does not contain an even digit.
+ */
+ if (last < 0) {
+ continue;
+ }
+ digits [last] --;
+
+ /*
+ * Print the output
+ */
+ for (ssize_t i = NR_OF_DIGITS - 1; i >= 0; i --) {
+ for (int j = 0; j < digits [i]; j ++) {
+ printf ("%zu", i);
+ }
+ }
+ printf ("%d\n", last);
+
+ }
+ free (line);
+
+ return (0);
+}